任务调度操作符
任务调度操作符在 DispatchQueue
、RunLoop
中采用,可确定订阅任务执行顺序
import Foundation
import Combine
let firstStepDone = DispatchSemaphore(value: 0)
/*:
## `receive(on:)`
- determines on which scheduler values will be received by the next operator and then on
- used with a `DispatchQueue`, lets you control on which queue values are being delivered
*/
print("Demonstrating receive(on:)")
let publisher = PassthroughSubject<String, Never>()
let receivingQueue = DispatchQueue(label: "receiving-queue")
let subscription = publisher
.receive(on: receivingQueue)
.sink { value in
print("Received value: \(value) on thread \(Thread.current)")
if value == "Four" {
//firstStepDone.signal()
}
}
for string in ["One","Two","Three","Four"] {
DispatchQueue.global().async {
publisher.send(string)
}
}
firstStepDone.wait()
如上例,将firstStepDone.signal()
注释掉后,或许如果还有其他的任务将无法继续,因为firstStepDone.wait()
将会阻塞。
输出:
Demonstrating receive(on:)
Received value: One on thread <NSThread: 0x60000171cec0>{number = 6, name = (null)}
Received value: Two on thread <NSThread: 0x60000171cec0>{number = 6, name = (null)}
Received value: Three on thread <NSThread: 0x60000171cec0>{number = 6, name = (null)}
Received value: Four on thread <NSThread: 0x60000171cec0>{number = 6, name = (null)}
去掉firstStepDone.signal()
的注释后再添加其他任务:
/*:
## `subscribe(on:)`
- determines on which scheduler the subscription occurs
- useful to control on which scheduler the work _starts_
- may or may not impact the queue on which values are delivered
*/
print("Demonstrating subscribe(on:)")
let subscription2 = [1,2,3,4,5].publisher
.subscribe(on: DispatchQueue.global())
.handleEvents(receiveOutput: { value in
print("Value \(value) emitted on thread \(Thread.current)")
})
.receive(on: receivingQueue)
.sink { value in
print("Received value: \(value) on thread \(Thread.current)")
}
输出:
Demonstrating receive(on:)
Received value: Three on thread <NSThread: 0x600001b224c0>{number = 4, name = (null)}
Received value: Two on thread <NSThread: 0x600001b224c0>{number = 4, name = (null)}
Received value: One on thread <NSThread: 0x600001b224c0>{number = 4, name = (null)}
Received value: Four on thread <NSThread: 0x600001b224c0>{number = 4, name = (null)}
Demonstrating subscribe(on:)
Value 1 emitted on thread <NSThread: 0x600001b224c0>{number = 4, name = (null)}
Value 2 emitted on thread <NSThread: 0x600001b224c0>{number = 4, name = (null)}
Received value: 1 on thread <NSThread: 0x600001b2ed00>{number = 5, name = (null)}
Value 3 emitted on thread <NSThread: 0x600001b224c0>{number = 4, name = (null)}
Received value: 2 on thread <NSThread: 0x600001b2ed00>{number = 5, name = (null)}
Value 4 emitted on thread <NSThread: 0x600001b224c0>{number = 4, name = (null)}