Skip to content

Instantly share code, notes, and snippets.

@manas-sharma-1683
Created February 9, 2021 21:16
Show Gist options
  • Save manas-sharma-1683/a04fa21e5aa1698a55e91c5204ed5677 to your computer and use it in GitHub Desktop.
Save manas-sharma-1683/a04fa21e5aa1698a55e91c5204ed5677 to your computer and use it in GitHub Desktop.
Future initializer that can accept throwing expressions.
import Combine
import Foundation
extension Future where Failure == Error {
convenience init(promise: @escaping (@escaping (Result<Output, Failure>) -> Void) throws -> Void) {
self.init({ (innerPromise) in
do {
try promise { innerPromise($0) }
} catch {
innerPromise(.failure(error))
}
})
}
}
var tokens = Set<AnyCancellable>()
Future<User, Error> { (promise) in // Error here if Future<User, Error> is changed to Future<User, Never>
let user = try JSONDecoder().decode(User.self, from: Data())
promise(.success(user))
}.sink(receiveCompletion: {
print($0)
}, receiveValue: {
print($0)
}).store(in: &tokens)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment