I'm studying Combine Scheduler and I have this example code from Raywenderlich book
let queue = OperationQueue()
let subscription = (1...10).publisher
.receive(on: queue)
.sink { value in
print("Received \(value) on thread \(Thread.current.number)")
}
The book is explaining that OperationQueue uses all available threads so the print order and thread could be random. I understand that part but when I run this code in my playground, I see only 5 numbers out of 10.
Received 1 on thread 7
Received 2 on thread 6
Received 3 on thread 5
Received 7 on thread 9
Received 6 on thread 4
Why that code doesn't show all 10 numbers??
You need to import
PlaygroundSupport
and setPlaygroundPage.current.needsIndefiniteExecution = true
at the top of the file.If you use the other sink method, the one that you also get a completion handler block for, then in that completion handler you should call
PlaygroundPage.current.finishExecution()
Edit: Call
PlaygroundPage.current.finishExecution()
in a barrier block on the queue, otherwise that gets called before your print statements all execute.Here's my testing code:
And the output: