Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In RxJava, how to pass a variable along when chaining observables?

I am chaining async operations using RxJava, and I'd like to pass some variable downstream:

Observable    .from(modifications)    .flatmap( (data1) -> { return op1(data1); })    ...    .flatmap( (data2) -> {         // How to access data1 here ?        return op2(data2);    }) 

It seems like a common pattern but I couldn't find information about it.

like image 604
Julian Go Avatar asked Jan 27 '15 17:01

Julian Go


People also ask

What is onNext in RxJava?

onNext. An Observable calls this method whenever the Observable emits an item. This method takes as a parameter the item emitted by the Observable. onError. An Observable calls this method to indicate that it has failed to generate the expected data or has encountered some other error.


1 Answers

The advice I got from the Couchbase forum is to use nested observables:

Observable     .from(modifications)     .flatmap( (data1) -> {          return op1(data1)             ...             .flatmap( (data2) -> {                  // I can access data1 here                 return op2(data2);             })         }); 

EDIT: I'll mark this as the accepted answer as it seems to be the most recommended. If your processing is too complex to nest everything you can also check the solution with function calls.

like image 56
Julian Go Avatar answered Sep 25 '22 10:09

Julian Go