Merging Observable: RxJava2

Observable.merge()

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

val observableSource1 : Observable<String> =  Observable.just("1", "2")val observableSource2  : Observable<String> =  Observable.just("3", "4")val observableSource3  : Observable<String> =  Observable.just("5", "6")val observableSource4  : Observable<String> =  Observable.just("7", "8")val observableSource5 : Observable<String> =  Observable.just("9", "10")
Observable.merge(observableSource1, observableSource2)
.subscribe {item->
Log.d(TAG, "received string : $item")
}

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()

Observable.concat(observableSource1, observableSource2)
.subscribe {item->
Log.d(TAG, "received string : $item")
}
Observable.mergeArray(observableSource1,
observableSource2,
observableSource3,
observableSource4,
observableSource5)
.subscribe {item->
Log.d(TAG, "received string : $item")
}
val sources: List<Observable<String>> = listOf(observableSource1, observableSource2, observableSource3, observableSource4, 
observableSource5)
// pass list to merge
Observable.merge(sources).subscribe {
Log.e(TAG, "received string :- $it")
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Gaurav Rajput

Gaurav Rajput

Working remotely as Android Developer