RxJava Merge Operator

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

I am Amit Shekhar, I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.

Join my program and get high paying tech job: amitshekhar.me

Before we start, I would like to mention that, I have released a video playlist to help you crack the Android Interview: Check out Android Interview Questions and Answers.

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

Prepare yourself for Android Interview: Android Interview Questions

That's it for now.

Thanks

Amit Shekhar

You can connect with me on:

Read all of my high-quality blogs here.