Search code examples
rx-javareactive-programmingrx-androidreactivex

Getting the initial emission of an Observable later in its tree


Given a hot Observable<String> myObservable which emit values at irregular intervals. I would like to be able to flatMap an obs1 Observable and depending on the result of obs1 I want to flatMap an obs2 with the initial myObservable value. As an example consider the code below:

myObservable
   .flatMap(stringResult -> myObject.getObs1(stringResult))
   .flatMap(result -> {
              if (result) {
                    myObject.getObs2(stringResult); // Here I would like to get stringResult emitted by myObservable but I can't
              } else {
                    Observable.just(result); // We continue with the "same" initial Observable 
              }
   });

A solution would be to store the myObservable in a variable and get its latest value in the second flatMap but I wasn't able to achieve this neither so I'm looking for a more elegant solution. Thank you.


Solution

  • You can put the second flatMap into the function of the first flatMap like this:

        myObservable.flatMap(stringResult -> {
                    return myObject.getObs1(stringResult).flatMap(result -> {
                        if (result) {
                            myObject.getObs2(stringResult);
                        } else {
                            Observable.just(result);
                        }
                    });
                });