Created
February 16, 2023 19:22
-
-
Save gordonbrander/d9a5ef55a2f8e57d878980ec4cae583e to your computer and use it in GitHub Desktop.
DispatchQueue.future
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 | |
import Combine | |
extension DispatchQueue { | |
/// Run a closure on a dispatch queue asyncronously. | |
/// - Returns a future. | |
func future<Output>( | |
perform: @escaping () -> Output | |
) -> Future<Output, Never> { | |
Future<Output, Never> { promise in | |
self.async { | |
let output = perform() | |
promise(Result.success(output)) | |
} | |
} | |
} | |
/// Run a throwing closure on a dispatch queue asyncronously. | |
/// - Returns a future. | |
func future<Output>( | |
perform: @escaping () throws -> Output | |
) -> Future<Output, Error> { | |
Future<Output, Error> { promise in | |
self.async { | |
do { | |
let output = try perform() | |
promise(Result.success(output)) | |
} catch { | |
promise(Result.failure(error)) | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment