RxJava Concat Operator

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

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

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

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

What is Concat Operator?

The Concat operator emits the emissions from two or more observables without interleaving them.

It maintains the order of the observables while emitting the items. It means that it will emit all the items of the first observable and then it will emit all the items of the second observable and so on.

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

RxJava Concat marble diagram

In the above diagram:

  • We have two source observables.
  • The first observable is emitting the items as 1, 1, and 1.
  • The second observable is emitting items as 2 and 2.
  • After applying the Concat operator, it is emitting all the items of the first observable and then all the items of the second observable. Hence, it is 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 Concat operator:

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

Here the output will be the following:

A1
A2
A3
A4
B1
B2
B3
B4

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

Now we have understood the Concat Operator of RxJava.

Note: Concat Operator maintains the order of the observables while emitting the items.

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

Learn about RxJava Merge Operator: RxJava Merge 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.