Created
December 29, 2020 19:24
-
-
Save OCJvanDijk/67e38e475d56b3574916686de9e5d0bc to your computer and use it in GitHub Desktop.
ProgressFuture
This file contains hidden or 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
class ProgressFuture<Output, Failure: Error> { | |
let future: Future<Output, Failure> | |
let progress: Progress | |
init(_ attemptToFulfill: @escaping (@escaping Future<Output, Failure>.Promise, Progress) -> Void) { | |
let progress = Progress() | |
self.future = Future { promise in attemptToFulfill(promise, progress) } | |
self.progress = progress | |
} | |
} | |
func example() { | |
let progressView = UIProgressView() | |
let task = ProgressFuture<String, Error> { promise, progress in | |
DispatchQueue.global().async { | |
do { | |
progress.totalUnitCount = 1000 | |
for i in 1...1000 { | |
progress.completedUnitCount = Int64(i) | |
if progress.isCancelled { | |
throw GenericError.cancelled | |
} | |
} | |
promise(.success("Success!")) | |
} catch { | |
promise(.failure(error)) | |
} | |
} | |
} | |
// Do something with future | |
task.future.replaceError(with: "Failed").sink { | |
print($0) | |
} | |
// And with the progress | |
progressView.observedProgress = task.progress | |
// Even cancel it | |
task.progress.cancel() | |
} | |
enum GenericError: Error { | |
case cancelled | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment