Created
January 27, 2020 07:33
-
-
Save rjchatfield/b1b4cd84373c28bc691835339713e25c to your computer and use it in GitHub Desktop.
Swift async/await interopt
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
/// Async code (one day) can be written in 3 ways: | |
/// 1. Callbacks | |
/// 2. Future | |
/// 3. async/await | |
/// | |
/// Let's explore how they work together by defining | |
/// `myClosure`, `myFuture` & `myFunction` | |
/// each derived from the other two approaches. | |
// Closure -> Future | |
let myFuture = Future<Value, Error> { callback in | |
myClosure(callback: { result in | |
callback(result) | |
}) | |
} | |
// or point-free style: | |
let myFuture = Future(block: myClosure(callback:)) | |
// Closure -> Async/Await | |
let value = await suspendAsync { continuation, onError in | |
myClosure(callback: { result in | |
switch result { | |
case .success(let value): | |
continuation(value) | |
case .failure(let error): | |
onError(error) | |
} | |
}) | |
} | |
// Future -> Closure | |
func myClosure(callback: @escaping (Result<Value, Error>) -> Void) { | |
myFuture | |
.onSuccess { value in | |
callback(.success(value)) | |
} | |
.onFailure { error in | |
callback(.failure(error)) | |
} | |
} | |
// Future -> Async/Await | |
let value = try await myFuture.getAsync() | |
// Async/Await -> Closure | |
func myClosure(callback: @escaping (Result<Value, Error>) -> Void) { | |
beginAsync { | |
do { | |
let value = try await myFunction() | |
callback(.success(value)) | |
} catch { | |
callback(.failure(error)) | |
} | |
} | |
} | |
// Async/Await -> Future | |
let myFuture = Future { try await myFunction() } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment