Say, you just learned RxSwift and all about subscribeNext
. You have a series of Harry Potter related service calls to make and they affect each other. Let’s also say they all return the same type of Observable<Person>
. So, you start to call these services one after another using subscribeNext
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
func startThePlotOld() { heroService.fetchBabyHarry().subscribeNext { baby in print("fetched baby") deliveryService.deliverToMuggles(baby).subscribeNext { baby in print("baby that was delivered was \(baby.name)") heroService.growBaby(baby, years: 10).subscribeNext { boy in print("baby \(boy.name) is grown") heroService.sendLettersTo(boy).subscribeNext { boy in print("letters sent") deliveryService.deliverToTrainStation(boy).subscribeNext { (boy) in print("\(boy.name) is on the train.") } } } } } } |
The indention of calls is known as the Pyramid of Doom. This is a case of not using all of the power that RxSwift offers. If we inject flatMapLatest
into the mix instead of all subscribeNext
calls, we get the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
func startThePlot() { heroService.fetchBabyHarry().flatMapLatest { baby -> Observable<Person> in print("fetched baby") return deliveryService.deliverToMuggles(baby) }.flatMapLatest { (baby) -> Observable<Person> in print("baby that was delivered was \(baby.name)") return heroService.growBaby(baby, years: 10) }.flatMapLatest { (boy) -> Observable<Person> in print("baby \(boy.name) is grown") return heroService.sendLettersTo(boy) }.flatMapLatest { (boy) -> Observable<Person> in print("letters sent") return deliveryService.deliverToTrainStation(boy) }.subscribeNext { boy in print("\(boy.name) is on the train.") }.addDisposableTo(disposeBag) } |
Not only is the flatMapLatest
approach easier to read, but one can see easily where the addDisposableTo(disposeBag)
should be added at the end to manage the memory.
This concept is also covered in the RxSwift Tips document. Enjoy all that RxSwift has to offer!