The Transforming Operators in RxSwift

Tram Ho

In the previous article I wrote about combined operators, this time it will be transforming operators. These are also very useful operators and often used in the process we work.


This operator is very similar to regular swift. With RxSwift, the map operator will convert each item that the source emits and return an Observable that emits the results that have been performed on the operations we convert in the closure of the map.

Compared to the array operator’s cousin map :

  • Use closures as an argument
  • Execute on each word of the array
  • Returns a new array that each element has been converted

We can see some differences here are quite small, the mechanism is almost the same. Try with an example to convert Int elements emit to String.


flatMap is the operator that will convert each Observable item to source into multiple Observables , then merge them into one target Observable.

This image may still confuse many, but try the following example:

To interpret the steps to output, it would look like this:

We can see that each emit item will be transformed into an Observable, then they will be merge again on the target Observale. So we need to note that they can be alternating and do not guarantee the order of the items.


If you already understand flatMap, congratulations because flatMapLatest is just a little different from its predecessor. The difference is, if its generous flatMap brother flatMap the intermediate Observables, it will get back all that the Intermediate Obserables emit. The flatMapLatest younger flatMapLatest disposes old Intermediate Obserables and accepts only emit items from Latest Intermediate Obserables . Okay, let’s try this picture.

As you can see, there are a total of 6 items emit from the Intermediate Obserables . If flatMap is the item, the green square item will be emit after the blue square diamond item. As for flatMapLatest , by the time the blue square diamond item emits, it has dispose 2 Intermediate Obserables red and blue, this time will only observe the blue items emitted. That’s why we won’t get a green square item at the Observable đích .

Above are some Transforming operators that I find useful, but I also use them. Hope the article can help you understand them and use them fluently.


Share the news now

Source : Viblo