Combine latest

Another useful operator to know is .combineLatest(). It can be used to merge items from multiple Observables in a very similar way that .zip() is used, but instead of waiting for values to be produced by both the Observables, it produces new values every time one of the Observables emits an item.

When a value is produced from one of the Observable, the previous value of the other Observable is retrieved and instantly a new item from .combineLatest() is produced.

Let's explore an example:

Observable.combineLatest(
Observable.just("One", "Two", "Three"),
Observable.interval(1, TimeUnit.SECONDS),
(number, interval) -> number + "-" + interval)
.subscribe(e -> log("subscribe", e));

This will produce the following output:

APP: subscribe:RxComputationThreadPool-1:Three-0
APP: subscribe:RxComputationThreadPool-1:Three-1
APP: subscribe:RxComputationThreadPool-1:Three-2
APP: subscribe:RxComputationThreadPool-1:Three-3
APP: subscribe:RxComputationThreadPool-1:Three-4
APP: subscribe:RxComputationThreadPool-1:Three-5

We will note that there were more items than three produced; this is because Observable.interval() is never terminated and always keeps producing new values. The other thing that begs our attention is the fact that we can see only the three elements used--One and Two are never in the play because the .just() Observable completed before the first value was produced from the Observable.interval().

However, consider that we use the following:

Observable.combineLatest(
Observable.interval(500, TimeUnit.MILLISECONDS),
Observable.interval(1, TimeUnit.SECONDS),
(number, interval) -> number + "-" + interval
)
.subscribe(e -> log("subscribe", e));

The output will be much more diverse, as in here:

APP: subscribe:RxComputationThreadPool-2:0-0
APP: subscribe:RxComputationThreadPool-1:1-0
APP: subscribe:RxComputationThreadPool-2:1-1
APP: subscribe:RxComputationThreadPool-1:2-1
APP: subscribe:RxComputationThreadPool-1:3-1
APP: subscribe:RxComputationThreadPool-2:3-2
APP: subscribe:RxComputationThreadPool-1:4-2

This operator, in general, is useful in cases there is a need to constantly produce a new updated value whenever one of the dependencies changes. For example, in a settings pane, when one of the switches get changed, then, there is a need to fetch an updated data from the server.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.177.86