iosswiftreactive-programmingrx-swiftreactive-cocoa

RxSwift -- MainScheduler.instance vs MainScheduler.asyncInstance


What is the difference between using RxSwift's MainSchedule.instance and MainSchedule.asyncInstance within the context of observeOn?


Solution

  • asyncInstance guarantees asynchronous delivery of events whereas instance can deliver events synchronously if it’s already on the main thread.

    As for why you would ever need to force asynchronous delivery when you’re already on the main thread: it’s fairly rare and I would typically try to avoid it, but sometimes you have a recursive reactive pipeline where one event triggers the delivery of a new event in the same pipeline. If this happens synchronously, it breaks the Rx contract and RxSwift will spit out a warning that you tried to deliver a second event before the first event finished. In this case you can observe on MainScheduler.asyncInstance to break the cycle.