1

I'm trying to test out some async stream but I'm not sure I am understanding them correctly. I have the following two example functions:

func foo() async throws { print("Start") for await data in bar() { print(data) } print("End") } private func bar() -> AsyncStream<String> { return AsyncStream { continuation in print("Stream Started") for count in 0...2 { sleep(1) print("Yielding...") continuation.yield("\(count)") } continuation.finish() } } 

I would have expected this to print something like this:

Start Stream Started Yielding... 0 Yielding... 1 Yielding... 2 End 

However what I am seeing is:

Start Stream Started Yielding... Yielding... Yielding... 0 1 2 End 

Is my expectation wrong here on how this stream should work?

3
  • 2
    At least never ever sleep this antique way. You undermine the async functionality. There is a native non-blocking way to wait for a moment. Commented Dec 18, 2022 at 16:32
  • @vadian appears that was the cause. My antique coding skills caused the problem :-) Commented Dec 18, 2022 at 16:41
  • The more interesting and much more subtle question is, how would the console log look like, if you would remove sleep() or the corrected version with Task.sleep(for:). ;) Commented Dec 20, 2022 at 16:04

1 Answer 1

2

There are 2 kinds of sleep, one for the thread (you are using this one)

https://developer.apple.com/documentation/foundation/thread/1413673-sleep

and the one that must be used in concurrency.

https://developer.apple.com/documentation/swift/task/sleep(_:)

private func bar() -> AsyncStream<String> { return AsyncStream { continuation in let task = Task{ print("Stream Started") for count in 0...2 { //Concurrency version of sleeping try await Task.sleep(for: .seconds(1)) print("Yielding...") continuation.yield("\(count)") } continuation.finish() } continuation.onTermination = { _ in //Make sure you cancel the task if the stream is terminated task.cancel() } } } 

Concurrency isn't directly related to threads, it is more about "Actors"

https://developer.apple.com/wwdc21/10132

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.