IdentifiableContinuation

0.0.3

Swift continuation that conforms to Identifiable and includes a cancellation handler.
swhitty/IdentifiableContinuation

What's New

Async Handlers

2023-05-24T22:34:04Z

Adds support for async closures, making it easy to store the continuations within an actor:

let val: String? = await withIdentifiableContinuation {
  await someActor.insertContinuation($0)
} onCancel: {
  await someActor.cancelContinuation(for: $0)
}

The onCancel: handler is still guaranteed to be called after the continuation body executes to completion, even if the task is already cancelled.

Build Codecov Platforms Swift 5.8 License Twitter

Introduction

IdentifiableContinuation is a lightweight wrapper around CheckedContinuation and UnsafeContinuation that conforms to Identifiable and includes an easy to use cancellation handler with the id.

Installation

IdentifiableContinuation can be installed by using Swift Package Manager.

Note: IdentifiableContinuation requires Swift 5.7 on Xcode 14+. It runs on iOS 13+, tvOS 13+, macOS 10.15+, Linux and Windows. To install using Swift Package Manager, add this to the dependencies: section in your Package.swift file:

.package(url: "https://github.com/swhitty/IdentifiableContinuation.git", .upToNextMajor(from: "0.0.1"))

Usage

Usage is similar to existing continuations:

let val: String = await withIdentifiableContinuation { 
    $0.resume(returning: "bar")
}

The continuation includes an id that can be attached to an asynchronous task enabling the onCancel handler to cancel it.

let val: String? = await withIdentifiableContinuation { continuation in
  foo.startTask(for: continuation.id) { result
     continuation.resume(returning: result)
  }
} onCancel: { id in
  foo.cancelTask(for: id)
}

async closures can be used making it easy to store the continuations within an actor:

let val: String? = await withIdentifiableContinuation {
  await someActor.insertContinuation($0)
} onCancel: {
  await someActor.cancelContinuation(for: $0)
}

Note: The onCancel: handler is guaranteed to be called after the continuation body even if the task is already cancelled. Manually check Task.isCancelled before creating the continuation to prevent performing unrequired work.

Checked/UnsafeContinuation

IdentifiableContinuation internally stores either a checked or unsafe continuation.

CheckedContinuation is used by the default methods:

  • withIdentifiableContinuation
  • withThrowingIdentifiableContinuation

UnsafeContinuation is used by the unsafe methods:

  • withIdentifiableUnsafeContinuation
  • withThrowingIdentifiableUnsafeContinuation

Credits

IdentifiableContinuation is primarily the work of Simon Whitty.

(Full list of contributors)

Description

  • Swift Tools 5.7.0
View More Packages from this Author

Dependencies

  • None
Last updated: Sat Sep 23 2023 03:13:36 GMT-0900 (Hawaii-Aleutian Daylight Time)