While using RxJava for UI development I found out that there two main usecases for combining two (and possibly more) Observable sequences with different frequencies of emitting items. They are: combining one-to-one and one-to-many.
For example, there is text field, emitting new values upon edit, and a button,
emitting click, we want to run some action after user entered some text and
clicked the button.
Text field generally emits more items than button, because new item is emitted for each change of field value.
Both sequences A and B emit items with nearly the same frequency.
For each item from A we expect one item from B.
To combine such sequences we can use operator zip.
Observable.zip(A, B, func2)
In this case for each item from sequence A we expect sequence B to emit multiple items.
These multiple items from B can be processed in two different ways.
Process every item
But there are not enough items from A to combine with B. To solve this can be used following operators:
Observable.combineLatest(A, B, func2)
Proccess only one item
Some of the items will be dropped then. This can be achieved with following operators:
- sample returns most recently emitted item within interval defined by other
Here we return most recently emitted item from B when item in A arrives.
This operator doesn't combine items, but sometimes can be used in the same way.
Reduce frequency of emitting items
In this case some items from observable B will be dropped.
- throttleFirst returns only first emitted item during specified time period
Observable.zip(A, B.throttleFirst(100, TimeUnit.MILLISECONDS), func2)
- throttleLast same as throttleFirst but returning last value
Note, that both of these operators by default operate on other Scheduler, so if you are using them in UI, do not forget to
before doing any UI related stuff.
In RxJava there is a termin "Backpressure", which describes how frequently observable emits and how fast they are processed by operator. For details about backpressure refer to official wiki.