13.RxSwift 调度者(下)

370 阅读2分钟
1. CurrentThreadScheduler

表示当前线程的Scheduler,默认使用的线程。那他是如何获取当前线程的呢: 以subscribe为例,看一下

这里先判断当前线程是否已经关联过:

  1. 如果关联过直接CurrentThreadScheduler.instance.schedule(()) 通过schedule()调用queue使用当前关联的线程key获取并返回一个queue

  1. 如果没有关联则:CurrentThreadScheduler.isScheduleRequired 通过isScheduleRequired设置一个线程调度key
    Thread拓展了两个存取线程调度key的方法:
    其中,当有当前线程调度key的时候会调用schedule(),返回一个ScheduledItem:
    ScheduledItem初始化过程会保存stateaction,最后在invoke()的时候调用
2. MainScheduler

MainScheduler 是主线程,我们要执行的一些和UI相关的操作就需要切换到主线程,它继承于SerialDispatchQueueScheduler(串行), 初始化的过程保存了一个线程_mainQueue: DispatchQueue,这个queue就是主线程self._mainQueue = DispatchQueue.main

3. SerialDispatchQueueScheduler

它封装了GCD的串行队列,如果我们需要执行一些串行任务,可以切换到这个Scheduler,初始化通过configuration -> DispatchQueueConfiguration 进行了一系列的多线程配置:

4. ConcurrentDispatchQueueScheduler

它封装了GCD的并行队列,如果我们需要执行一些并行任务,可以切换到这个Scheduler,初始化通过configuration -> DispatchQueueConfiguration 进行了一系列的多线程配置:

5. OperationQueueScheduler

它封装了NSOperation,初始化通过configuration -> DispatchQueueConfiguration 进行了一系列的多线程配置:

6. 简单使用
* SerialDispatchQueueScheduler
    Observable.of(1,2,3,4,5,6,7,8,9,10)
                .observeOn(SerialDispatchQueueScheduler.init(internalSerialQueueName: "observeOnSerial"))
                .subscribe{print("observeOn",$0,Thread.current)}
                .disposed(by: self.bag)
* ConcurrentDispatchQueueScheduler
    Observable.of(
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100)
                .subscribeOn(ConcurrentDispatchQueueScheduler.init(qos: .background))
                .subscribe{print("subscribeOn",$0,Thread.current)}
                .disposed(by: self.bag)
* OperationQueueScheduler
    let opQueue = OperationQueue.init()
            Observable.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100)
                .subscribeOn(OperationQueueScheduler.init(operationQueue: opQueue))
                .subscribe{print("subscribeOn",$0,Thread.current)}
                .disposed(by: self.bag)