Created
January 26, 2024 11:52
-
-
Save mattmassicotte/e8d5b4f73d2545222decd61ccdc348bd to your computer and use it in GitHub Desktop.
MainActor + AsyncSequence
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
@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