Created
December 18, 2022 08:39
-
-
Save DavidBemerguy/0be9cecb1af1564d65cc892ebb9c276c to your computer and use it in GitHub Desktop.
Swift NullableContinuation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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