RxAndroid 2.0.1 订阅方法不设置变量

RxAndroid 2.0.1 subscribe method doesnt set a variable

好的,我对 android 和响应式编程还很陌生,过去两天我一直在尝试制作一个 activity 从服务器获取帖子并将它们加载到 Post[] 稍后在我的应用程序中使用。这里的问题是,当我将 Post[] 传递给 displayPostsMethod 时,它为空。这是 Activity

中的代码
public class HomeActivity extends AppCompatActivity{
        private Post[] postsToDisplay;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_home);

                //get the posts from the server
                this.getPostsFromServer();

                //dispaly the posts
                this.displayPosts(posts);// here are the posts null
        }

        public void getPostsFromServer() {
                PostsProvider.getAllPosts()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(posts -> {
                    this.postsToDispaly = Arrays.copyOf(posts, posts.length);
                });
        }
    }

这也是 PostsProvider class.

中 getAllPostsMethod 的代码
public static Observable<Post[]> getAllPosts(){
    return Observable.create((ObservableEmitter<Post[]> e) -> {
      OkHttpClient client = new OkHttpClient();

      Request request = new Request.Builder()
          .url("sample url")
          .build();

      Response response = client.newCall(request).execute();

      String json = response.body().string();

      Gson gson = new Gson();

      Post[] posts = gson.fromJson(json, Post[].class);
      e.onNext(posts);
    });
  }

首先,检查下面几行的顺序

 //get the posts from the server
 this.getPostsFromServer();

 //dispaly the posts
 this.displayPosts(posts);

好的,所以您正在调用 'getPostFromServer' 方法,然后调用 displayPosts 但问题是 getPostFromServer 就像一个 AsnycTask,由于这条线 运行 它会在后台 运行

 .subscribeOn(Schedulers.io())
 .observeOn(AndroidSchedulers.mainThread())
 .subscribe(posts -> {
         this.postsToDispaly = Arrays.copyOf(posts, posts.length);
 });

在 RxJava 中订阅 says-> 我想在后台 运行 以上行(Schedulers.io() on io thread)和 observeOn(主线程)以及当你订阅的时候相当于在异步任务中调用execute

因此 android 系统将在后台执行并获取结果,因此另一种方法(显示 post)暂时不会获取 posts 通过在方法显示 post 和订阅结果接收时间

中添加日志来检查此逻辑

你可以更好地从订阅中调用显示 posts 像这样

.subscribe(posts -> {
                if(posts!=null)//check i think null will not be received in Rxjava 2.0 so also add error method in which you can show no result to be displayed
                displayPosts(posts);
            },err->{//add no posts found here and dismiss progress dialog/progress bar
                    err.printStackTrace();
              });

在您执行 API 调用之前,您可以显示进度对话框或进度条

检查线程系统是如何工作的,它在 RxJava 中是相同的逻辑,所以如果你可以检查 AsyncTask 和 doInBackground 基本逻辑是相同的,可以在不停止用户交互的情况下在后台执行某些操作。