RxSwift -- MainScheduler.instance vs MainScheduler.asyncInstance
Asked Answered
U

1

15

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

Unthrone answered 11/10, 2019 at 0:7 Comment(5)
@Cristik The main difference per the documentation is that the asyncInstance "always schedules work asynchronously". Does that mean that the regular instance sometimes does work asynchronously, but not always? Ultimately I would like to understand when and why to use one over the other. cocoadocs.org/docsets/RxSwift/2.4/Classes/MainScheduler.html#/…Unthrone
Per the docs, use asyncInstance if you want the events to always be delivered asynchronously even if you’re already on the main thread. instance may deliver events synchronously if you’re already on the main thread.Unmerciful
Thanks @jjoelson. Under what circumstances would it be desirable for events to always be delivered asynchronously? From my understanding — and I’m very new to RxSwift — calling observeOn using the MainScheduler will guarantee that the event processing you provide (typically UI) will occur on the Main Thread. If that’s true, then why wouldn’t you want events to arrive synchronously? Is it to prevent frequently occurring event from clogging the main thread? If you have some iOS examples or use cases for both instances, that would be helpful and much appreciated.Unthrone
@Unthrone I put it in an answer. Let me know if that’s not clear enough!Unmerciful
That makes sense. I'll try to whip up some code that does what you described to see how asyncInstance can be used to break the cycle. Thanks @jjoelson!Unthrone
U
28

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.

Unmerciful answered 11/10, 2019 at 22:44 Comment(1)
What a great explanation! Thanks you so much!Nel

© 2022 - 2024 — McMap. All rights reserved.