简体   繁体   中英

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?

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);
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM