Skip to content

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

License

Notifications You must be signed in to change notification settings

swhitty/IdentifiableContinuation

Repository files navigation

Build Codecov Platforms Swift 6.0 License Twitter

Introduction

IdentifiableContinuation is a lightweight wrapper around CheckedContinuation 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.10 on Xcode 15.4+. 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.3.0"))

Usage

With Swift 6, usage is similar to existing continuations.

let val: String = await withIdentifiableContinuation { 
  continuations[$0.id] = $0
}

The body closure is executed syncronously within the current isolation allowing actors to mutate their isolated state.

An optional cancellation handler is called when the task is cancelled. The handler is @Sendable and can be called at any time after the body has completed.

let val: String = await withIdentifiableContinuation { 
  continuations[$0.id] = $0
} onCancel: { id in
  // @Sendable closure executed outside of actor isolation requires `await` to mutate actor state
  Task { await self.cancelContinuation(with: id) }
}

The above is also compatible in Swift 5 language mode using a Swift 6 compiler e.g. Xcode 16

Swift 5

While behaviour is identical, Swift 5 compilers (Xcode 15) are unable to inherit actor isolation through the new #isolation keyword (SE-420) so an isolated reference to the current actor must always be passed.

let val: String = await withIdentifiableContinuation(isolation: self) { 
  continuations[$0.id] = $0
}

Credits

IdentifiableContinuation is primarily the work of Simon Whitty.

(Full list of contributors)

About

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

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published