Transform: FlatMap and ConcatMap
Learn about transforming operators like FlatMap and ConcatMap.
We'll cover the following...
FlatMap
The .flatMap()
operator is another very common operator used to transform emissions from an Observable
. The stream is transformed by applying a function that we specify to each emitted item. However, unlike .map()
, the function specified should return an object of type Observable
. The returned Observable
is then immediately subscribed to and the sequence emitted by that Observable
is then merged and flattened along with subsequent emissions, which are then passed along to the Observer
.
Example
A common real-world example of using .flatMap()
is for implementing nested network calls. Say we have an Observable<User>
, and for each User
, we’d like to make a network call to retrieve that user’s detailed information.
Assume we have the following methods available:
Observable<User> getUser(int userId) {// Return an Observable<User> that performs a network// request to retrieve a User with ID `userId`}Observable<UserDetail> getUserDetail(User user) {// Return an Observable<UserDetail> that performs a// network request to retrieve details about `user`}
Chaining ...