On the change "SortBy", my program will do a NetworkIO to retrieve the top movies and display them.
However, it seems that though I have done subscribeOn(Schedulers.io()), the NetworkIO MovieDB.getPopular() and MovieDB.getTopRated() in the function call in map are excuted on the main thread and I get a android.os.NetworkOnMainThreadException.
I was wondering how to make the public Movie[] call(SortBy sortBy) asynchronous.
sortObservable.map(new Func1<SortBy, Movie[]>() {
@Override
public Movie[] call(SortBy sortBy) {
try {
switch (sortBy) {
case POPULAR:
return MovieDB.getPopular(); // NETWORK IO
case TOP_RATED:
return MovieDB.getTopRated(); // NETWORK IO
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return new Movie[0];
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Movie[]>() {
@Override
public void call(Movie[] movies) {
imageAdapter.loadData(movies);
}
});
flatMapinstead, and wrap your io calls in an observable.subscribeOnis wheresubscribeis called. UseobserveOnto control the thread of the previous observable.android.os.NetworkOnMainThreadException, source code here: github.com/zizhengwu/Popular-Movies-Stage-1/blob/load-image/app/…fromCallableinstead, so you can give it a thread to use when subscribed tocallableandfromCallablewith my map function. Could you provide some code for me?