1

Ok I am fairly new to android and reactive programming and I have been trying for the past two days to make an activity that gets posts from a server and loads them into a Post[] that is later used in my app. The problem here is that when I pass that Post[] to the displayPostsMethod it is null. Here is the code in the 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);
                });
        }
    }

And here is also the code from the getAllPostsMethod in PostsProvider class.

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);
    });
  }
Hristian Iliev
  • 19
  • 1
  • 11

1 Answers1

2

First, Check the sequence of lines below

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

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

ok so you're calling 'getPostFromServer' method and then displayPosts but the thing is getPostFromServer is like an AsnycTask it will run in the background due to this line

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

Here in RxJava subscribe on says-> I want to run the above lines in background (Schedulers.io() on io thread) and observeOn (main thread) and when you subscribe the thing it is equivalent to call execute in async task

So android system will execute and get results in background so another method (display post) will not get the posts at a time being check this logic by adding logs in methods display post and subscribe result received time

better you can call display posts from subscribe like this

.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();
              });

and until you do API call you can show progress dialog or progress bar

Check how threading system works and It's same logic in RxJava so if you can check AsyncTask and doInBackground basic logic is same to execute something in the background without stopping user interactions.

Parth Dave
  • 2,096
  • 13
  • 20
  • I hope your question is solved, if not comment me i will help you out – Parth Dave Dec 15 '17 at 17:37
  • ok but what if i want to store the data that i get from the subscribe() and then use it for exampleto pass it somewhere. Also maybe i am doing something wrong but it still throws NullPointerException. Is it better to use AsuncTask with doInBackground – Hristian Iliev Dec 15 '17 at 17:42
  • can you debug here Post[] posts = gson.fromJson(json, Post[].class); e.onNext(posts); I don't think so that your getting posts from here print json and posts in above line before onNext() and what is the exact error? – Parth Dave Dec 15 '17 at 18:09
  • i recently found out that the lines of code in the subscribe method get executed later than i use the postsToDisplay array and because of that it is null. So my next question how to make the app wait until the subscribe method gets executed and the array is set. – Hristian Iliev Dec 15 '17 at 18:17
  • If I dont wrong, your goal is to wait for variable change then do some action right? See this answer https://stackoverflow.com/questions/38738760/android-rxjava-subscribe-to-a-variable-change – Putra Christianto Purba Dec 15 '17 at 18:30
  • actually you need to show something like progressbar to user and await task that are dependent on that result and call another method and run tasks or methods you want to call in subscribe result – Parth Dave Dec 15 '17 at 18:36