Search code examples
iosswiftrx-swiftreactivex

Question about a custom RxSwift Observable extension


extension Observable {
    func dispatchAsyncMainScheduler() -> Observable<E> {
        return self.observeOn(backgroundScheduler).observeOn(MainScheduler.instance)
    }
}

I found this snippet in https://github.com/artsy/eidolon

I am a reactive beginner here. From what I understand. subscribeOn applies to the whole chain whereas the observeOn applies operators below it.

My question is quite obvious, what exactly does this two consecutive observeOn do at all?


Solution

  • It's not a typo. If you look at the definition of backgroundScheduler 10 lines above this operator, you will see that it's a SerialDispatchQueueSceduler. This means that it queues up operations and performs them in order on a background thread.

    They are using it to avoid reentrancy anomalies. I'll assume that this code was written before MainScheduler.asyncInstance was put in the library, which does the same thing.

    More info can be found in the Rx library:

    • Problem: This behavior is breaking the observable sequence grammar. next (error | completed)? This behavior breaks the grammar because there is overlapping between sequence events. Observable sequence is trying to send an event before sending of previous event has finished.
    • Interpretation: This could mean that there is some kind of unexpected cyclic dependency in your code, or that the system is not behaving in the expected way.
    • Remedy: If this is the expected behavior this message can be suppressed by adding .observeOn(MainScheduler.asyncInstance) or by enqueing sequence events in some other way.