top of page

Chaining Completable Sequence in RxSwift

  • Writer: Jennifer Eve Vega
    Jennifer Eve Vega
  • Nov 11, 2022
  • 1 min read


When using completable and .andThen() — it sometimes performs the second observable sequence even the first one has not gotten back with success response yet.


Imagine calling two consecutive APIs. One API has to be called first, and we need to pass some values based on the response (from the first API call) to the second API call.


Chaining Completable Sequence:

func myFirstCompletable() -> Completable {
	// API call
}

func mySecondCompletable() -> Completable {
	// API call
}
self.myFirstCompletable()
.andThen(self.mySecondCompletable())
.subscribe()
.disposed(by: self.bag)

You will notice that with the code above, mySecondCompletable() function was called already even though myFirstCompletable() has not given us a success/failed response yet.


Fix: Use deferred

To fix this, use Completable.deferred so that it will wait for the first observable sequence before calling the 2nd one.


self.myFirstCompletable()
.andThen(Completable.deferred(self.mySecondCompletable()))
.subscribe()
.disposed(by: self.bag)

Comments


©2021 by The Average Programmer. Proudly created with Wix.com

bottom of page