Convert AsyncTask to RxAndroid

Fshamri picture Fshamri · Jul 23, 2015 · Viewed 8.3k times · Source

I have the following method to post response to UI using otto and AsyncTask.

private static void onGetLatestStoryCollectionSuccess(final StoryCollection storyCollection, final Bus bus) {
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            bus.post(new LatestStoryCollectionResponse(storyCollection));
            return null;
        }
    }.execute();
}

I need help to convert this AsyncTask to RxJava using RxAndroid library.

Answer

Tarek360 picture Tarek360 · May 26, 2016

Don't use .create() but use .defer()

Observable<File> observable = Observable.defer(new Func0<Observable<File>>() {
  @Override public Observable<File> call() {

    File file = downloadFile();

    return Observable.just(file);
  }
});

to know more details see https://speakerdeck.com/dlew/common-rxjava-mistakes