merge() operator

The merge() operator takes data from different streams and combines it. Here is the thing though: these streams can be of any kind as long as they are of type Observable. This means we can combine data from a timing operation, a promise, static data from an of() operator, and so on. What merging does is to interleave the emitted data. This means that it will emit from both streams at the same time in the following example. Using the operator comes in two flavors, as a static method but also as an instance method:

// combination/merge.js

let promiseStream = Rx.Observable
.from(new Promise(resolve => resolve("data")))

let stream = Rx.Observable.interval(500).take(3);
let stream2 = Rx.Observable.interval(500).take(5);

// instance method version of merge(), emits 0,0, 1,1 2,2 3, 4
stream.merge(stream2)
.subscribe(data => console.log("merged", data));

// static version of merge(), emits 0,0, 1,1, 2, 2, 3, 4 and 'data'
Rx.Observable.merge(
stream,
stream2,
promiseStream
)
.subscribe(data => console.log("merged static", data));

The takeaway here is that if you just need to combine one stream with another, then use the instance method version of this operator, but if you have several streams, then use the static version. Furthermore, the order in which the streams are specified matters.

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

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