Created
February 9, 2021 21:16
-
-
Save manas-sharma-1683/a04fa21e5aa1698a55e91c5204ed5677 to your computer and use it in GitHub Desktop.
Future initializer that can accept throwing expressions.
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 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