Last active
August 2, 2024 09:33
-
-
Save pookjw/d91083e3f9add70cefa5f1345d5bb244 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension AsyncStream { | |
@discardableResult | |
func yield(_ value: __owned Element) -> AsyncStream<Element>.Continuation.YieldResult { | |
let context = (Mirror(reflecting: self).descendant("context")! as AnyObject?)! | |
let storage = (Mirror(reflecting: context).descendant("storage")! as AnyObject?)! | |
let continuation = unsafeBitCast(storage, to: Self.Continuation.self) | |
_ = Unmanaged.passRetained(storage) | |
return continuation.yield(value) | |
} | |
} | |
@main | |
struct MyScript { | |
static func main() async { | |
let stream: AsyncStream<Int> = .init { _ in } | |
Task.detached { | |
while true { | |
try? await Task.sleep(for: .seconds(1)) | |
stream.yield(Int.random(in: 0...100)) | |
} | |
} | |
for await value in stream { | |
print(value) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Other (complicated) consideration