RxJava Operator - Map Vs FlatMap

Amit Shekhar
MindOrks
Published in
2 min readMay 17, 2018
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.

Components of the 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.

Map Operator

FlatMap

FlatMap transforms the items emitted by an Observable into Observables.

FlatMap Operator

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.

Map Example

Here, the observable gives us ApiUser object which we are converting into User object by using the map operator.

FlatMap Example

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.

--

--

Amit Shekhar
MindOrks

Co-Founder @ Outcome School | Coder | Teacher | Mentor | Open Source | IIT 2010-14 | Android | Machine Learning | Backend