【发布时间】:2023-10-04 10:07:01
【问题描述】:
从一个类中给出下面的代码:
cancellable = input
.receive(on: scheduler)
.map { ... }
.sink(receiveValue: { value in
self.state = value
})
其中input 是 PassthroughSubject。
现在,当scheduler 是主队列或将从主线程调用 RunLoop.main AND 输入时,receive(on: scheduler) 是否会以编程方式优化对主队列的显式分派?
所以,基本上是这样的:
if Thread.isMainThread {
/* execute closure */
} else {
/* dispatch closure async to main */
}
receive(on:) 的文档给出了一个模糊的提示,它可能会执行一些优化:
“首选接收(on:options :)而不是显式使用调度队列”
pub.sink {
DispatchQueue.main.async {
// Do something.
}
}
【问题讨论】: