RxSwift Scheduler

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)")
            return Disposables.create()
        .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background))
        .map({ (n) -> Int in
            print("==A \(Thread.current)")
            return n + 10
        .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
        .subscribe(onNext: { (text) in
            print("==D \(Thread.current)")
            print("got \(text)")
        }, onError: nil, onCompleted: nil, onDisposed: nil)

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

About Tang

A mobile developer, work in Stockholm, Sweden
This entry was posted in iOS, React and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s