RxSwfit: Scheduler

什么是 Scheduler ?

Scheduler 就是一个程序上下文发生的地方,它可以是一个线程,一个 dispatch queue 或者 NSOperation,例如下面的图片所示:

RxSwfit: Scheduler_第1张图片
image.png

阐明 Scheduler

有一个错误的观点就是 schedulers 等价于一个 thread,这样看起来好像很合理,schedulers 就像 GCD.

但是如果以自定义 scheduler 的时候,可以创建多个 scheduler 使用相同的线程

RxSwfit: Scheduler_第2张图片
explicit

这里要记住的是 schedulers 并不是线程,它也没有和线程有一一对应的关系

下面是例子用到的一些代码


fileprivate func secondsElapsed() -> String {
  return String(format: "%02i", Int(Date().timeIntervalSince(start).rounded()))
}

extension ObservableType {
  func dump() -> RxSwift.Observable {
    return self.do(onNext: { element in
      let threadName = getThreadName()
      print("\(secondsElapsed())s | [D] \(element) received on \(threadName)")
    })
  }
  
  func dumpingSubscription() -> Disposable {
    return self.subscribe(onNext: { element in
      let threadName = getThreadName()
      print("\(secondsElapsed())s | [S] \(element) received on \(threadName)")
    })
  }
}

接下来写下如下代码


let fruit = Observable.create { (observer) -> Disposable in
    observer.onNext("[apple]")
    sleep(2)
    observer.onNext("[pineapple]")
    sleep(2)
    observer.onNext("[strawberryy]")
    return Disposables.create()
}

输入如下


00s | [D] [apple] received on Main Thread
00s | [S] [apple] received on Main Thread
02s | [D] [pineapple] received on Main Thread
02s | [S] [pineapple] received on Main Thread
04s | [D] [strawberryy] received on Main Thread
04s | [S] [strawberryy] received on Main Thread

使用 subscribeOn

有时候要改变 schedule 的 observable 的运行的地方。创建一个 scheduler,然后改成如下代码

let globalScheduler = ConcurrentDispatchQueueScheduler(queue: DispatchQueue.global())

fruit
    .subscribeOn(globalScheduler)
    .dump()
    .dumpingSubscription()
    .addDisposableTo(bag)
    
RunLoop.main.run(until: Date(timeIntervalSinceNow: 13))
    

输出如下

00s | [D] [apple] received on Anonymous Thread
00s | [S] [apple] received on Anonymous Thread
02s | [D] [pineapple] received on Anonymous Thread
02s | [S] [pineapple] received on Anonymous Thread
04s | [D] [strawberryy] received on Anonymous Thread
04s | [S] [strawberryy] received on Anonymous Thread

使用 observeOn

把代码改成如下:

fruit
    .subscribeOn(globalScheduler)
    .dump()
    .observeOn(MainScheduler.instance)
    .dumpingSubscription()
    .addDisposableTo(bag)
    

输出:

00s | [D] [apple] received on Anonymous Thread
00s | [S] [apple] received on Main Thread
02s | [D] [pineapple] received on Anonymous Thread
02s | [S] [pineapple] received on Main Thread
04s | [D] [strawberryy] received on Anonymous Thread
04s | [S] [strawberryy] received on Main Thread


你可能感兴趣的:(RxSwfit: Scheduler)