In this article I’ll introduce an RxJS flatMap() operator. Previous articles in this series include:
1. Basic Terms
2. Operators map, filter, and reduce
3. Using Observable.create()
4. Using RxJS Subject
In some cases, you need to treat each item emitted by an observable as another observable. In other words, the outer observable emits the inner observables. Does it mean that we need to write nested subscribe() calls (one for the outer observable and another for the inner one)? No, we don’t. The flatMap() operator takes each item from the outer observable and auto-subscribes to it.
Some operators are not explained well in RxJS documentation, and we recommend you to refer to the general ReaciveX (reactive extensions) documentation for clarification. The flatMap() operator is better explained there, and it states that flatMap() is used to “transform the items emitted by an observable into observables, then flatten the emissions from those into a single observable”. This documentation includes the following marble diagram:
As you see, the flatMap() operator takes an emitted item from the outer observable (the circle) and unwraps its content (the inner observable of diamonds) into the flattened output observable stream. The flatMap() operator merges the emissions of the inner observables so their items may interleave.
The following code listing has an observable that emits drinks, but this time it emits not individual drinks, but palettes. The first palette has beers and the second – soft drinks. Each palette is observable. We want to turn these two palettes into an output observable with individual beverages.
function getDrinks() { let beers = Rx.Observable.from([ // 1 {name: "Stella", country: "Belgium", price: 9.50}, {name: "Sam Adams", country: "USA", price: 8.50}, {name: "Bud Light", country: "USA", price: 6.50} ], Rx.Scheduler.async); let softDrinks = Rx.Observable.from([ // 2 {name: "Coca Cola", country: "USA", price: 1.50}, {name: "Fanta", country: "USA", price: 1.50}, {name: "Lemonade", country: "France", price: 2.50} ], Rx.Scheduler.async); return Rx.Observable.create( observer => { observer.next(beers); // 3 observer.next(softDrinks); // 4 observer.complete(); } ); } // We want to "unload" each palette and print each drink info getDrinks() .flatMap(drinks => drinks) // 5 .subscribe( // 6 drink => console.log("Subscriber got " + drink.name + ": " + drink.price ), error => console.err(error), () => console.log("The stream of drinks is over") );
1. Creating an async observable from beers
2. Creating an async observable from soft drinks
3. Emitting the beers observable with next()
4. Emitting the soft drinks observable with next()
5. Unloading drinks from pallets into a merged observable
6. Subscribing to the merged observable
This script will produce the output that may look as follows (note that the drinks interleave):
Subscriber got Stella: 9.5 Subscriber got Coca Cola: 1.5 Subscriber got Sam Adams: 8.5 Subscriber got Fanta: 1.5 Subscriber got Bud Light: 6.5 Subscriber got Lemonade: 2.5 The stream of observables is over
To see it in CodePen visit this link.
Are there any other uses of the flatMap() operator besides unloading palettes of drinks? Another scenario where you’d want to use flatMap() is when you need to execute more than one HTTP request, where the result of the first request should be given to the second one. In Angular, HTTP requests return observables and without flatMap() this could be done (it a bad style) with nested subscribe() calls:
this.httpClient.get('/customers/123') .subscribe(customer => { this.httpClient.get(customer.orderUrl) .subscribe(response => this.order = response) })
The method httpClient.get() returns an observable, and the better way to write the above code is by using the flatMap() operator, which auto-subscribes and unwraps the content of the first observable and makes another HTTP request:
httpClient.get('./customers/123') .flatMap(customer => this.httpClient.get(customer.orderURL)) .subscribe(response => this.order = response);
Since a flatMap() is a special case of map(), you can specify a transforming function while flattening the observables into a common stream. In the above example, we transform the value customer into a function call httpClient.get().
TIP: In RxJS, flatMap() is an alias of mergeMap() so these two operators have the same functionality.
Let’s consider one more example of using flatMap(). This example will be a modified version of the traders-orders example used in the article “Using RxJS Subject“. This example is written in TypeScript and it uses two Subject instances:
* traders – this Subject keeps track of traders
* orders – this Subject is declared inside the class Trader and keeps track of each order placed by a particular trader.
You’re the manager who wants to monitor all orders placed by all traders. Without flatMap(), you’d need to subscribe to traders (the outer observable) and create a nested subscription for orders (the inner observable) that each subject has. Using flatMap() allows you to write just one subscribe() call, which will be receiving the inner observables from each trader in one stream.
import {Subject} from 'rxjs/Subject'; import 'rxjs/add/operator/mergeMap'; enum Action{ Buy = 'BUY', Sell = 'SELL' } class Order{ constructor(public orderId: number, public traderId: number, public stock: string, public shares: number, public action:Action){} } let traders = new Subject<Trader>(); // 1 class Trader { orders = new Subject<Order>(); // 2 constructor(private traderId:number, public traderName:string){} } let tradersSubscriber = traders.subscribe(trader => console.log(`Trader ${trader.traderName} arrived`)) let ordersSubscriber = traders // 3 .flatMap(trader => trader.orders) // 4 .subscribe(ord => // 5 console.log(`Got order from trader ${ord.traderId} to ${ord.action} ${ord.shares} shares of ${ord.stock}`)); let firstTrader = new Trader(1, 'Joe'); let secondTrader = new Trader(2, 'Mary'); traders.next(firstTrader); traders.next(secondTrader); let order1 = new Order(1, 1,'IBM',100,Action.Buy); let order2 = new Order(2, 1,'AAPL',200,Action.Sell); let order3 = new Order(3, 2,'MSFT',500,Action.Buy); // Traders place orders firstTrader.orders.next( order1); firstTrader.orders.next( order2); secondTrader.orders.next( order3);
1. Declare the Subject for traders
2. Each trader has its own Subject for orders
3. Starting with the outer observable traders
4. Extracting the inner observable from each Trader instance
5. The function subscribe() receives a stream of orders
In this version of the program, the class Trader doesn’t have a method placeOrder(). We just have the trader’s observable orders push the order to its observer by using the method next(). Remember, a Subject has both observable and observer.
The output of this program is shown next.
Trader Joe arrived Trader Mary arrived Got order from trader 1 to BUY 100 shares of IBM Got order from trader 1 to SELL 200 shares of AAPL Got order from trader 2 to BUY 500 shares of MSFT
In our example, the subscriber just prints the orders on the console, but in a real world app it could invoke another function that would be placing orders with the stock exchange for execution.
To see it in CodePen, follow this link. In the next article you’ll learn about a very useful operator switchMap().
5 thoughts on “RxJS Essentials. Part 5: The flatMap operator”