Merging Observable: RxJava2

Sometimes we need to merge two or more observable emitting the same type of items T. In RxJava, we have some operator to do so.

Let’s see how we can do that:

Observable.merge()

merge() operator can merge 2 to 4 observable sources of the same type T.

let’s merge the first two with merge() operator:

Output:

received string : 1

received string : 2

received string : 3

received string : 4

Note: Here emission of items seems sequential, but it’s not true if they are cold observable and on the same thread

Now if you want to make sure sequential emission of items, we should use Observable.concat()

Merge using concat() operator:

The output will be sequential.

What if the user wants to merge more then four observable of the same type?

For that, we have mergeArray(), operator.

Cant we use merge() operator for more than 4 observable in any way. For that we can pass Iterable<Observable<T>>

Let’s see by example:

Create a list of above observables :

The output is the same as above.

To summarize, Observable.merge() will combine multiple Observable<T> sources emitting the same type T and consolidate into a single Observable<T>.

Working remotely as Android Developer