0

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.

E-Kami
  • 2,529
  • 5
  • 30
  • 50

1 Answers1

1

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);
                    }
                });
            });
zsxwing
  • 20,270
  • 4
  • 37
  • 59