Rx’s flatMap is not what you think!

David Öhman
2 min readNov 22, 2020

The learning curve of RxJava

I have been programming for Android professionally for almost two years, and RxJava/RxAndroid took me the longest time to understand enough to be able to manage it by myself.

I’m not going to introduce you to Rx, I assume you know the basics like Observables emitting data and you subscribe to them but still don’t understand Rx generally.

The operator flatMap

I will take you directly to the turning point — where it all began to make sense to me. I often saw this in the code project: Observable.flatMap(). I didn’t understand it because, of course, I assumed it was Collections.flatMap(), which mapped lists into a single list.

But, then something happened, I decided to ask a senior fellow at my work to clarify the flatMap operator of Rx. He replied — “You do know it’s not the same as Collections.flatMap, don’t you?” this was when the penny dropped. I wish I knew this much earlier.

But, what does that Observable.flatMap() do then?

Very good question. I will simply go by this simple description provided by the documentation:

Transform the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable

Say you want to subscribe to fetchUserObservable, but you would need an accessToken from the loginObservable first. So, you can do this — subscribe to loginObservable and then use its response, which is the accessToken, to the fetchUserObservable. Like the example below:

authRepo.loginObservable
.flatMap { accessToken ->
// accessToken is from loginObservable
userRepo.fetchUserObservable(accessToken)
}
.subscribe { user ->
// user is from fetchUserObservable
print(user)
}

That was a trivial example, but hopefully clear. You can connect how many Observables into each other you want using flatMap. Let me repeat:

Rx’s flatMap is not the same as the flatMap you know from the Collections class!

--

--