Skip to content

Instantly share code, notes, and snippets.

@mattmassicotte
Created January 26, 2024 11:52
Show Gist options
  • Save mattmassicotte/e8d5b4f73d2545222decd61ccdc348bd to your computer and use it in GitHub Desktop.
Save mattmassicotte/e8d5b4f73d2545222decd61ccdc348bd to your computer and use it in GitHub Desktop.
MainActor + AsyncSequence
@MainActor
final class UsesAsyncSequence {
func original() {
let stream = AsyncStream { 42 }
Task {
// Passing argument of non-sendable type
// 'inout AsyncStream<Int>.Iterator' outside of main
// actor-isolated context may introduce data races
for await value in stream {
processValue(value)
}
}
}
func possibleFix() {
let stream = AsyncStream {
return 42
}
// explicitly remove the actor inheritance so the iterator does not need to hop
// between MainActor and non-isolated
Task.detached {
for await value in stream {
await self.processValue(value)
}
}
}
func processValue(_ value: Int) {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment