Search code examples
rxjsrx-javarx-swiftreactivex

Progressive image loading with ReactiveX


I'm trying to load a downsized preview image, followed by a hires image. I want to make sure that if by any chance the hires image gets loaded first, the preview image is discarded.

Consider the following examples, where:

  • Sequence 1 is preview image requests
  • Sequence 2 is hires image requests
  • Sequence 3 is the combined sequence
  • Sequence 4 is the resulting image rendering sequence

.

Example 1:

 1    ------P-------
 2    ---------H----

 3    ------P--H----

 4    ------*--*----


Example 2:

 1   ----H---------
 2   --------P-----

 3   ----H|--------

 4   ----*|--------

The only solution I've come up with so far is saving a state variable which denotes whether the hires has been loaded already and using takeWhile, but this requires some non-elegant manipulations and also involves side effects.

I'm looking for the correct RX way to do so.


Solution

  • You can do it without saving state and using variable:

    Observable<Bitmap> hiresObservable = getHiresObservable()
            .share()
    Observable<Bitmap> previewObservable = getPreviewObservable()
            .takeUntil(hiresObservable);
    
    
    Observable.merge(previewObservable, hiresObservable)
          .subscribe(bitmap -> {
               //do something with the bitmap
          });
    

    this is very much similar to this answer.