RxJava Concat Operator
- Authors
- Name
- Amit Shekhar
- Published on
I am Amit Shekhar, Co-Founder @ Outcome School, 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 Outcome School and get high paying tech job: Outcome School
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 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.
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
Prepare yourself for Android Interview: Android Interview Questions
That's it for now.
Thanks
Amit Shekhar
Co-Founder @ Outcome School
You can connect with me on:
Follow Outcome School on: