Search code examples
javarxjsrx-javarx-android

Combine Observable with second Observable which uses results from from the first one


I have two methods returning Observable:

Observable<String> firstObservable();
Observable<String> secondObservable(String value);

For each result from the first Observable I get new instance of the second Observable. For each result from the second observable I would return object with combined results.

firstObservable ->  x----x----x----x----x
                     \    \    \    \    \
secondObservable ->   y(x)-y(x)-y(x)-y(x)-y(x)
                      \     \     \     \     \
result ->             {x,y}-{x,y}-{x,y}-{x,y}-{x,y}

How can this be done?


Solution

  • There's an overloaded variant of flatMap, the second argument of which is the combining function that has access to the initial item and the one produced by the second observable:

    firstObservable.flatMap(string -> secondObservable(string), (s, s2) -> s + s2);