RxJava Operator - Map Vs FlatMap

Amit Shekhar
May 17, 2018 · 3 min read
RxJava Operator: Map vs FlatMap

RxJava is the most important library which is popular among the 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.

Components of the RxJava

The above diagram describes what each component do.

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.

Video tutorial for this blog post

MindOrks Youtube

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 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.

Learn about the Concat Vs Merge Operator

Learn “How to implement caching using RxJava Operators”

That’s it for now. Happy learning :)

Recommended Reading

MindOrks

Our community publishes stories worth reading on Android Development

Amit Shekhar

Written by

Co-Founder at MindOrks & AfterAcademy | Changing the way developers learn | EdTech | IIT 2010–14 | Medium Top Writer | Android Dev | https://amitshekhar.me

MindOrks

MindOrks

Our community publishes stories worth reading on Android Development

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade