RxAndroid
is another better alternative to this problem and it saves us from hassles of creating threads and then posting results on Android UI thread.
We just need to specify threads on which tasks need to be executed and everything is handled internally.
Observable<List<String>> musicShowsObservable = Observable.fromCallable(new Callable<List<String>>() {
@Override
public List<String> call() {
return mRestClient.getFavoriteMusicShows();
}
});
mMusicShowSubscription = musicShowsObservable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<List<String>>() {
@Override
public void onCompleted() { }
@Override
public void onError(Throwable e) { }
@Override
public void onNext(List<String> musicShows){
listMusicShows(musicShows);
}
});
By specifiying
(Schedulers.io())
,RxAndroid will rungetFavoriteMusicShows()
on a different thread.By using
AndroidSchedulers.mainThread()
we want to observe this Observable on the UI thread, i.e. we want ouronNext()
callback to be called on the UI thread