RxJava Operator - Map Vs FlatMap
RxJava is the most important library which is popular among Android developers. It makes our life easy.
New content: System Design Playlist
I am Amit Shekhar, Co-Founder @ Outcome School, the author of this blog. This blog will help you understand the difference between Map and FlatMap.
We use RxJava for multithreading, managing background tasks, and removing callback hells. We can solve so many complex use cases with the help of RxJava. It enables us to do complex things very simply. It provides us the power.
With great power comes great responsibility
Let’s see the components of RxJava.
The above diagram describes what each component does.
Operator: An operator is like a translator who translates/modifies data from one form to another form.
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
Map transforms the items emitted by an Observable by applying a function to each item.
FlatMap
FlatMap transforms the items emitted by an Observable into Observables.
So, the main difference between Map and FlatMap is 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.
That’s it for now. Happy learning :)
Prepare yourself for Android Interview: Android Interview Questions
You can find the Roadmap for Android Developer here: Android Developer Roadmap
Thanks
Amit Shekhar
Co-Founder @ Outcome School
Also, let’s become friends on Twitter, Linkedin, Github, Quora, and Facebook.