0
votes

To better understand RxAndroid I found this Repo which is full of useful examples using RxAndroid, especially in combination with Retrofit.

So if I look at this part of the repo, I can make an http call by clicking an button which seems to be running in the background right?

What if I have this app which needs to show an activity/fragment and at the same time do some http call on the background and show the data if there is any received?

So for instance I have this fragment with onStart

@Override
public void onStart() {
    super.onStart();

    pomagistoService
            .getAgenda()
            .subscribeOn(Schedulers.newThread())    // <- run in background right?
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<List<Appointment>>() {
                @Override
                public void onCompleted() { }

                @Override
                public void onError(Throwable e) { }

                @Override
                public void onNext(List<Appointment> appointments) {
                    // show data in ListView
                }
            });
}

If I start this fragment a ListView instantaneously contains the data which is received by the http call.

Now the question/wondering I have is: Does this http call run in the background?

I am asking this because of the data which is there immediately when the fragment appears, so I can't really observe it.

2
yes the http call run in the background - Amit Shekhar
@AmitShekhar oke, so let's say the http call takes 5seconds, it won't take 5seconds for the fragment to appear? The fragment just appears (without data)? - Jim Vercoelen
you should update the fragment listview from the onNext() - Amit Shekhar
@AmitShekhar yeah yeah I know, am doing that! But because of the call is so fast the data is there before the fragment even had the change to show ;-p - Jim Vercoelen

2 Answers

0
votes

Usually, for network request you should use not Schedulers.newThread(), but Schedulers.io(). Also, to get some delay before request is executed and get a chance to see fragment without data try to use .delay(5, TimeUnit.SECONDS) to make 5 seconds delay before call.

0
votes

if you're using subscribeOn(Schedulers.io()) then you're telling RxJava to do its job in background (another thread). Schedulers.io() is usaually used for I/O operations like networking, you can use Schedulers.computation() for long processing operations running locally.

and by using observeOn(AndroidSchedulers.mainThread()) you're telling that you want to recieve the final result in the main thread so you can show it or handle ui events.

some common error is the confusion when using subscribeOn() and observeOn(), so to make it easy for you .. you're always want to observe results on main thread to reflect it in UI otherwise use what fit your case.