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)
}

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

GitHub

https://github.com/swhitty/IdentifiableContinuation