Contents

withUnsafeContinuation(isolation:_:)

Invokes the passed in closure with a unsafe continuation for the current task.

Declaration

func withUnsafeContinuation<T>(isolation: isolated (any Actor)? = #isolation, _ fn: (UnsafeContinuation<T, Never>) -> Void) async -> sending T

Parameters

  • fn:

    A closure that takes an UnsafeContinuation parameter.

Return Value

The value continuation is resumed with.

Discussion

The body of the closure executes synchronously on the calling task, and once it returns the calling task is suspended. It is possible to immediately resume the task, or escape the continuation in order to complete it afterwards, which will then resume the suspended task.

You must invoke the continuation’s resume method exactly once.

Missing to invoke it (eventually) will cause the calling task to remain suspended indefinitely which will result in the task “hanging” as well as being leaked with no possibility to destroy it.

Unlike the “checked” continuation variant, the UnsafeContinuation does not detect or diagnose any kind of misuse, so you need to be extra careful to avoid calling resume twice or forgetting to call resume before letting go of the continuation object.

See Also

Continuations