Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access to data from previous emission in rx?

Tags:

java

rx-java

The question is about rx programming. I have a code:

Observable.from(array)
          .map(array_item1 -> array_item2)
          .map(array_item3 -> array_item4)
          .map(array_item5 -> array_item6)

and in the third map call I need access not only array_item5 but also array_item1 or array_item3. it should seem like this:

...    
.map(array_item5 -> array_item5 + array_item1)
...

Is there any special pattern or an operator for this?

like image 950
rdo Avatar asked Mar 03 '16 01:03

rdo


1 Answers

If you want access previous emissions, you need save them somewhere. There is accumulator operators:

Collect - collects all emissions in single mutable structure

Observable.from(Arrays.asList(1,2,3,4,5,6))
      .collect(ArrayList::new,
        (array, item) -> {
            //access previous and current emissions
            array.add(item);
        })

Scan - in addition to collect, it returns all previous emissions on every next:

Observable.from(Arrays.asList(1,2,3,4,5,6))
    .scan(new ArrayList<>(), (array, item) -> {
           array.add(item)     
           return array;
          })
    .map(collectedItems -> {
          //access all previous and curent emissions on every new
          return collectedItems;
        })
like image 171
zella Avatar answered Oct 30 '22 20:10

zella