Last active
July 27, 2022 20:52
-
-
Save manmal/94aadc14c3e1baa36b64be42938e4b56 to your computer and use it in GitHub Desktop.
Swift Structured Concurrency - Task Auto Cancellation
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
public extension Task { | |
/// Cancels this `Task` when the surrounding `Task` is cancelled. | |
/// This is necessary if `Task {}` and `Task.detached {}` | |
/// should be automatically cancelled - otherwise, such Tasks | |
/// just run until finished. | |
/// | |
/// Usage: | |
/// | |
/// await Task { await myAsyncFunc() }.autoCancel() | |
func autoCancel() async -> Void { | |
await withTaskCancellationHandler( | |
handler: { self.cancel() }, | |
operation: { () } | |
) | |
} | |
/// Returns this `Task`'s result and cancels this `Task` when | |
/// the surrounding `Task` is cancelled. This is necessary if | |
/// `Task {}` and `Task.detached {}` should be automatically | |
/// cancelled - otherwise, such Tasks just run until finished. | |
/// | |
/// Usage: | |
/// | |
/// let result = await Task { await myAsyncFunc() } | |
/// .resultWithAutoCancel | |
var resultWithAutoCancel: Result<Success, Failure> { | |
get async { | |
await withTaskCancellationHandler( | |
handler: { self.cancel() }, | |
operation: { await self.result } | |
) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment