Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert AsyncTask to RxAndroid

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.

like image 903
Fshamri Avatar asked Jul 23 '15 15:07

Fshamri


People also ask

What is RxAndroid?

What is RxAndroid? RxAndroid is an extension of RxJava for Android which is used only in Android application. RxAndroid introduced the Main Thread required for Android. To work with the multithreading in Android, we will need the Looper and Handler for Main Thread execution. RxAndroid provides AndroidSchedulers.

What is the replacement for RxJava?

RxKotlin is basically the same as RxJava, it just adds some syntactic sugar to make it more comfortable / idiomatic writing RxJava code in Kotlin.


Video Answer


1 Answers

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

like image 187
Tarek360 Avatar answered Sep 23 '22 04:09

Tarek360