0

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.

Shahar
  • 478
  • 5
  • 17

1 Answers1

4

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.

Community
  • 1
  • 1
yosriz
  • 10,147
  • 2
  • 24
  • 38
  • because otherwise you'll subscribe twice to the hiresObservable which you don't want, share 'multicast' your Observable so multiple subscription will see the same values, actually you might need to be more careful and use other 'multicast' operator to prevent race (for instance if you hires has cache), you can read my explanation here: http://stackoverflow.com/a/42826568/3903847 – yosriz Apr 18 '17 at 17:11