Where we call subscribeOn() in a chain doesn't really matter when to call it. Where we call observeOn() does matter.
subscribeOn() tells the whole chain which thread to start processing on. We should only call it once per chain. If we call it again lower down the stream it will have no effect.
observeOn() causes all operations which happen below it to be executed on the specified scheduler. We can call it multiple times per stream to move between different threads.
@IBAction func rxSchedulerTest(_ sender: UIButton) {
print("==UI \(Thread.current)")
Observable.create { (observer: AnyObserver<Int>) -> Disposable in
print("==Observable \(Thread.current)")
observer.onNext(1)
observer.onCompleted()
return Disposables.create()
}
.subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background))
.map({ (n) -> Int in
print("==A \(Thread.current)")
return n + 10
})
.observeOn(MainScheduler.instance)
.map({ (m) -> String in
print("==B \(Thread.current)")
return String(m)
})
.observeOn(ConcurrentDispatchQueueScheduler(qos: .utility))
.map({ (text) -> String in
print("==C \(Thread.current)")
return "X" + text
})
.observeOn(MainScheduler.instance)
.subscribe(onNext: { (text) in
print("==D \(Thread.current)")
print("got \(text)")
}, onError: nil, onCompleted: nil, onDisposed: nil)
.addDisposableTo(disposeBag)
}
the output is
==UI <NSThread: 0x6100000748c0>{number = 1, name = main}
==Observable <NSThread: 0x60800007d400>{number = 3, name = (null)}
==A <NSThread: 0x60800007d400>{number = 3, name = (null)}
==B <NSThread: 0x6100000748c0>{number = 1, name = main}
==C <NSThread: 0x60800007d400>{number = 3, name = (null)}
==D <NSThread: 0x6100000748c0>{number = 1, name = main}
got X11
RxSwift Schedulers:
- ConcurrentDispatchQueueScheduler
- ConcurrentMainScheduler
- CurrentThreadScheduler
- DispatchQueueSchedulerQOS
- HistoricalScheduler
- HistoricalSchedulerTimeConverter
- MainScheduler
- OperationQueueScheduler
- SerialDispatchQueueScheduler
- VirtualTimeConverterType
- VirtualTimeScheduler
reference: http://cocoadocs.org/docsets/RxSwift/2.6.0/RxSwift/Schedulers.html#/s:C7RxSwift13MainScheduler