RxJava Merge Operator

Authors
  • Amit Shekhar
    Name
    Amit Shekhar
    Published on
RxJava Merge Operator

I am Amit Shekhar, a mentor helping developers in getting high-paying tech jobs.

In this blog, we will learn about the Merge operator of RxJava.

RxJava has operators for every use case. One of the very useful operators of RxJava is Merge Operator.

What is Merge Operator?

The Merge operator combines multiple Observables into one by merging their emissions. It will not maintain the order while emitting the items.

First, let's understand it through the marble diagram of the Merge operator.

RxJava Merge marble diagram

In the above diagram:

  • We have two source observables.
  • The first observable is emitting the items as 20, 40, 60, 80, and 100.
  • The second observable is emitting items as 1 and 1.
  • After applying the Merge operator, it is emitting the items from both the observables. But, it is not maintaining the order of the observables in which they were added.

Now, it's time to see the example code.

Our Observer:

fun getObserver(): Observer<String> {
    return object : Observer<String> {

        override fun onSubscribe(d: Disposable) {

        }

        override fun onNext(value: String) {
            println(value)
        }

        override fun onError(e: Throwable) {

        }

        override fun onComplete() {

        }
    }
}

Our Observables:

val observableA = Observable.fromArray("A1", "A2", "A3", "A4")
val observableB = Observable.fromArray("B1", "B2", "B3", "B4")

Applying Merge operator:

Observable.merge(observableA, observableB)
    .subscribe(getObserver())

Here the output will be the following:

A1
A2
B1
A3
B2
B3
A4
B4

As we have used the Merge Operator, it has not maintained the order and emitted the values as A1, A2, B1, A3, B2, B3, A4, and B4.

If we run the above example code again, it can produce different outputs.

Now we have understood the Merge Operator of RxJava.

Note: Merge Operator does not maintain the order of the observables while emitting the items.

This way we can use RxJava Merge Operator to solve any problem in a very simple way.

Learn about RxJava Concat Operator: RxJava Concat Operator

Master Kotlin Coroutines from here: Mastering Kotlin Coroutines

That's it for now.

Thanks

Amit Shekhar

You can connect with me on:

Read all of my high-quality blogs here.