Schedulers

Schedulers allow you to control to which queue RxSwift operators are dispatched. By default, all RxSwift operations are executed on the same queue where the subscription was made, but by using schedulers with observeOn and subscribeOn, you can alter that behavior. For example, you could subscribe to a stream whose events are emitted from a background queue, possibly the results of some lengthy tasks, and observe those events from the main thread to be able to update the UI based on those tasks' outcomes. Recalling our previous example, this is how we could use observeOn and subscribeOn as described:

 let aDisposableBag = DisposeBag()
let thisIsAnObservableStream = Observable.from([1, 2, 3, 4, 5, 6])
.observeOn(MainScheduler.instance).map { n in
print("This is performed on the main scheduler")
}

let subscription = thisIsAnObservableStream
.subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background))
.subscribe(onNext: { event in
print("Handle \(event) on main thread? \(Thread.isMainThread)")
}, onError: { print("Error: \($0). On main thread? \(Thread.isMainThread)")
}, onCompleted: { print("Completed. On main thread? \(Thread.isMainThread)") })

subscription.disposed(by: aDisposableBag)