Search code examples
swiftgrand-central-dispatchnsrunloopcombine

RunLoop vs DispatchQueue as Scheduler


When using new Combine framework you can specify the scheduler on which to receive elements from the publisher.

Is there a big difference between RunLoop.main and DispatchQueue.main in this case when assigning publisher to UI element? The first one returns the run loop of the main thread and the second queue associated with the main thread.


Solution

  • I've posted the similar question on the Swift Forum. I encourage you to see the discussion https://forums.swift.org/t/runloop-main-or-dispatchqueue-main-when-using-combine-scheduler/26635.

    I just copy and paste the answer from Philippe_Hausler

    RunLoop.main as a Scheduler ends up calling RunLoop.main.perform whereas DispatchQueue.main calls DispatchQueue.main.async to do work, for practical purposes they are nearly isomorphic. The only real differential is that the RunLoop call ends up being executed in a different spot in the RunLoop callouts whereas the DispatchQueue variant will perhaps execute immediately if optimizations in libdispatch kick in. In reality you should never really see a difference tween the two.

    RunLoop should be when you have a dedicated thread with a RunLoop running, DispatchQueue can be any queue scenario (and for the record please avoid running RunLoops in DispatchQueues, it causes some really gnarly resource usage...). Also it is worth noting that the DispatchQueue used as a scheduler must always be serial to adhere to the contracts of Combine's operators.