Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you do continuations with RxJava Observables?

So I have one async operation A that depends on a second, B. How do I make B a continuation of A as you would have with the then function Javascript Promises, or with ContinueWith in .NET TPL?

Let's take a scenarion from Android where I have two service endpoints:

  • One for fetching a URL for an image
  • One for fetching the image itself

Code:

private void loadImage(final ImageView imageView) {
    Observable<String> stringObs = getImageUrlAsync();
    stringObs.subscribe(new Action1<String> () {
        @Override
        public void call(String imageUrl) {
            // First async operation done
            Observable<Bitmap> bitmapObs = getBitmapAsync(imageUrl);
            bitmapObs.subscribe(new Action1<Bitmap>() {
                @Override
                public void call(Bitmap image) {
                    // second async operation done
                    imageView.setImageBitmap(image);
                }
            });
        }
    });
}

I would like not to have these two operations nested code-wise, but be in a format that reads more like it acts - sequentially.

I've been unable to find anything about continuations with regards to Observables in RxJava/RxAndroid. Can anyone please help?

like image 418
Nilzor Avatar asked Mar 02 '26 18:03

Nilzor


1 Answers

I think you need API flatMap

eg:

Observable.create(new Observable.OnSubscribe<String>() {
        @Override
        public void call(Subscriber<? super String> subscriber) {
            subscriber.onNext("imageUrl");
        }
    }).flatMap(new Func1<String, Observable<Bitmap>>() {
        @Override
        public Observable<Bitmap> call(String imageUrl) {
            return getBitmapAsync(imageUrl);
        }
    }).subscribe(new Action1<Bitmap>() {
        @Override
        public void call(Bitmap o) {
            imageView.setImageBitmap(image);
        }
    });
like image 87
baitouwei Avatar answered Mar 05 '26 08:03

baitouwei