Skip to content

Instantly share code, notes, and snippets.

@rjchatfield
Created January 27, 2020 07:33
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 rjchatfield/b1b4cd84373c28bc691835339713e25c to your computer and use it in GitHub Desktop.
Save rjchatfield/b1b4cd84373c28bc691835339713e25c to your computer and use it in GitHub Desktop.
Swift async/await interopt
/// 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