Skip to content

Instantly share code, notes, and snippets.

@manmal
Last active July 27, 2022 20:52
Show Gist options
  • Save manmal/94aadc14c3e1baa36b64be42938e4b56 to your computer and use it in GitHub Desktop.
Save manmal/94aadc14c3e1baa36b64be42938e4b56 to your computer and use it in GitHub Desktop.
Swift Structured Concurrency - Task Auto Cancellation
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