top of page
  • Writer's pictureJennifer Eve Vega

Chaining Completable Sequence in RxSwift



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)
234 views0 comments

Recent Posts

See All
bottom of page