19

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.

armatita
  • 12,825
  • 8
  • 48
  • 49
Fshamri
  • 1,346
  • 4
  • 17
  • 32

3 Answers3

13

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

Tarek360
  • 1,251
  • 1
  • 13
  • 19
  • This seems a little awkward to me. It's creating an Observable that outputs the already downloaded file, which by deferring the creation happens to be executed in the background. I believe Observable.fromCallable would be more appropriate. – Zackline Sep 25 '17 at 20:45
11

This is an example for a file download task using RxJava

Observable<File> downloadFileObservable() {
    return Observable.create(new OnSubscribeFunc<File>() {
        @Override
        public Subscription onSubscribe(Observer<? super File> fileObserver) {
            try {
                byte[] fileContent = downloadFile();
                File file = writeToFile(fileContent);
                fileObserver.onNext(file);
                fileObserver.onCompleted();
            } catch (Exception e) {
                fileObserver.onError(e);
            }
            return Subscriptions.empty();
        }
    });
}

Usage:

downloadFileObservable()
  .subscribeOn(Schedulers.newThread())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(observer); // you can post your event to Otto here

This would download the file on a new thread and notify you on the main thread.

OnSubscribeFunc was deprecated. Code updated to use OnSubscribe insted. For more info see issue 802 on Github.

Code from here.

Grzegorz Dev
  • 3,073
  • 1
  • 18
  • 22
LordRaydenMK
  • 13,074
  • 5
  • 50
  • 56
6

In your case you can use fromCallable. Less code and automatic onError emissions.

Observable<File> observable = Observable.fromCallable(new Callable<File>() {
        @Override
        public File call() throws Exception {
            File file = downloadFile();
            return file;
        }
    });

Using lambdas:

Observable<File> observable = Observable.fromCallable(() -> downloadFile());
Maksim Ostrovidov
  • 10,720
  • 8
  • 42
  • 57