FlatMap operators in RxSwift

Shohei Yokoyama
2 min readAug 3, 2017

--

I develop an iOS application using RxSwift in the project. I’d like to share tips to better understand RxSwift. This article describes the FlatMap operators.

FlatMap operators

RxSwift supports multiple FlatMap operators. You can find out marble diagram and detailed description here.

  • FlatMap
  • FlatMapLatest
  • FlatMapFirst
  • FlatMapWithIndex

FlatMap

The Document of flatMap is here. Look at following sample code.

FlatMap is similar to Map, but it transforms element of observable to an observable sequence. Also, The resulting observable sequences is merged with one observable sequence.

Therefore, FlatMap is useful, for example, if you want to create a new observable by using resulting of observable.

The following code is bad case.

If nested observable sequence is continuous, readability is bad and callback hell 😇

Next, following code is good case.

This code is clean and cool. 😎

FlatMapLatest and FlatMapFirst

What is the difference between these operator and flatMap ? 🤔

If operator produces observable sequence several times, flatMapLatest and flatMapFirst work differently from flatMap.

First, let’s look at example of flatMap .

When the first item( killua ) is emitted, The Level of player killua is printed out. Next, when killua’s level changes, A new level is printed out.

In addition, emit another player ( gon ) , Of course, gon’s level ( 50 ) is printed out. when gon’s level also changes, A new level is printed out.

Finally, let’s change level of killua. The value ( 52 ) then is printed out.

This is because every observable emitted by flatMap continues to be subscribed without being dispose. If disposeBag is released, every observable is released.

Next, following code is example of flatMapLatest.

The above works much the same as example of flatMap. But of interest at the last line. When level of killua is changed, nothing is printed out.

This is because flatMapLatest has already switched to the latest observable, for gon. when item is emitted, flatMapLatest ignores the previous one and begins emitting items emitted by the new one.

On the other hand, flatMapFirst emit only the first observable and ignores others as follows:

FlatMapWithIndex

The documentation for flatMapWithIndex describes that

Projects each element of an observable sequence to an observable sequence by incorporating the element’s index and merges the resulting observable sequences into one observable sequence.

By using index, you can control items emitted in the following way.

References

--

--

Shohei Yokoyama

【横山 祥平 / @shoheiyokoyama 】iOS Engineer at SmartNews, Inc. EX-CyberAgent, Inc, Github: https://github.com/shoheiyokoyama