您需要在文件顶部导入PlaygroundSupport
并设置。PlaygroundPage.current.needsIndefiniteExecution = true
如果您使用另一种接收器方法,也就是您还获得完成处理程序块的方法,那么在该完成处理程序中您应该调用PlaygroundPage.current.finishExecution()
编辑:PlaygroundPage.current.finishExecution()
在队列上调用障碍块,否则在您的打印语句全部执行之前调用。
这是我的测试代码:
PlaygroundPage.current.needsIndefiniteExecution = true
let queue = OperationQueue()
let subscription = (1...10).publisher
.receive(on: queue)
.sink(receiveCompletion: { _ in
queue.addBarrierBlock {
print("Finished")
PlaygroundPage.current.finishExecution()
}
}, receiveValue: { value in
print("Received \(value) on thread \(Thread.current)")
})
和输出:
Received 1 on thread <NSThread: 0x7fd86f204080>{number = 2, name = (null)}
Received 2 on thread <NSThread: 0x7fd86f404340>{number = 3, name = (null)}
Received 3 on thread <NSThread: 0x7fd86f404430>{number = 4, name = (null)}
Received 7 on thread <NSThread: 0x7fd86f405240>{number = 5, name = (null)}
Received 6 on thread <NSThread: 0x7fd86f205c50>{number = 6, name = (null)}
Received 10 on thread <NSThread: 0x7fd86ce487f0>{number = 7, name = (null)}
Received 5 on thread <NSThread: 0x7fd86cf048a0>{number = 10, name = (null)}
Received 9 on thread <NSThread: 0x7fd86ce49b20>{number = 11, name = (null)}
Received 4 on thread <NSThread: 0x7fd86cf2a4c0>{number = 12, name = (null)}
Received 8 on thread <NSThread: 0x7fd86ce4ad60>{number = 13, name = (null)}
Finished