RxJava is the most important library which is popular among Android developers. It makes our life easy.
We use RxJava for multithreading, managing background tasks, and removing callback hells. We can solve so many complex use-cases with the help of the RxJava. It enables us to do complex things very simple. It provides us the power.
With great power comes great responsibility
Let’s see the components of the RxJava.
The above diagram describes what each component does.
Operators: It translates the input into the required format of the output.
RxJava has so many operators. In order to use them correctly, we must know about them. Here, we will discuss the Map and the FlatMap.
Map transforms the items emitted by an Observable by applying a function to each item.
FlatMap transforms the items emitted by an Observable into Observables.
So, the main difference between Map and FlatMap that FlatMap mapper returns an observable itself, so it is used to map over asynchronous operations.
Very important: FlatMap is used to map over asynchronous operations.
Let’s see the example code.
Here, the observable gives us ApiUser object which we are converting into User object by using the map operator.
Here, we are getting the ApiUser and then we are making a network call to get the UserDetail for that apiUser by using the getUserDetailObservable(apiUser). The flatMap mapper returns an observable itself. The getUserDetailObservable is an asynchronous operation.
This is how we should use the Map and the FlatMap operators in RxJava.
Android App Development Online Course For Professionals
Join and learn Dagger, Kotlin, RxJava, MVVM, Architecture Components, Unit Testing, and much more.
That’s it for now. Happy learning :)