Swift AsyncStream迭代等待结束

eqfvzcg8  于 2022-12-22  发布在  Swift
关注(0)|答案(2)|浏览(107)

我试着测试一些异步流,但我不确定我是否正确理解了它们。我有以下两个示例函数:

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()
    }
}

我本以为这会打印出这样的内容:

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

然而,我看到的是:

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

我对这个流应该如何工作的期望是错误的吗?

bjp0bcyl

bjp0bcyl1#

sleep有两种,一种用于线程(您正在使用这一种)
https://developer.apple.com/documentation/foundation/thread/1413673-sleep
并且必须在并发中使用。
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()
        }
    }
}

并发与线程没有直接关系,它更多地与“参与者”有关
https://developer.apple.com/wwdc21/10132

9wbgstp7

9wbgstp72#

问题是使用sleep(1)而不是try await Task.sleep(nanoseconds: 1_000_000_000)

相关问题