Skip to content

Instantly share code, notes, and snippets.

@DavidBemerguy
Created December 18, 2022 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidBemerguy/0be9cecb1af1564d65cc892ebb9c276c to your computer and use it in GitHub Desktop.
Save DavidBemerguy/0be9cecb1af1564d65cc892ebb9c276c to your computer and use it in GitHub Desktop.
Swift NullableContinuation
import Foundation
/// API's out of our control can sometimes callback more than once, causing the continuation to crash
/// This class is a wrapper that should avoid this crash
/// Not recommended to be used largely, but it can help if really needed to use the problematic API
public class NullableContinuation<T, E> where E : Error {
private var checkedContinuation: CheckedContinuation<T,E>?
public init(checkedContinuation: CheckedContinuation<T,E>) {
self.checkedContinuation = checkedContinuation
}
public func resume(returning value: T) {
checkedContinuation?.resume(returning: value)
checkedContinuation = nil
}
}
public func withNullableContinuation<T>(_ body: (NullableContinuation<T, Never>) -> Void) async -> T {
await withCheckedContinuation { continuation in
let nullableContinuation = NullableContinuation(checkedContinuation: continuation)
body(nullableContinuation)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment