Alex Kokorin
Alex Kokorin

Reputation: 469

How can I merge 2 observables in a custom fashion?

Custom fashion is: obs1 = [1, 3, 5, 7, 9], obs2 = [2, 4, 6, 8, 10] -> mergedObs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

I was thinking about obs1.zipWith(obs2) and my bifunction was (a, b) -> Observable.just(a, b) and then it's not trivial for me to flatten Observable<Observable<Integer>>.

Upvotes: 0

Views: 38

Answers (1)

akarnokd
akarnokd

Reputation: 69997

That looks like an ordered merge: merge so that the smallest is picked from the sources when they all have items ready:

Flowables.orderedMerge():

Given a fixed number of input sources (which can be self-comparable or given a Comparator) merges them into a single stream by repeatedly picking the smallest one from each source until all of them completes.

Flowables.orderedMerge(Flowable.just(1, 3, 5), Flowable.just(2, 4, 6))
.test()
.assertResult(1, 2, 3, 4, 5, 6);

Edit

If the sources are guaranteed to be the same length, you can also zip them into a structure and then flatten that:

Observable.zip(source1, source2, (a, b) -> Arrays.asList(a, b))
.flatMapIterable(list -> list)
;

Upvotes: 3

Related Questions