Created
March 30, 2021 07:55
-
-
Save steipete/58b1c14ed73686ac66337a7aef1c9854 to your computer and use it in GitHub Desktop.
Combine helper that runs a Future after a delay on a background queue
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 | |
/// Run a block in the background with a delay and make it cancellable. | |
/// - Parameters: | |
/// - delay: Delay in milliseconds before the background work starts | |
/// - queue: Background queue to use | |
/// - worker: Worker block to execute on queue | |
/// - completion: Completion handler executed on main thread. | |
/// - Returns: AnyCancellable token | |
func runDelayedInBackground<Output>(delay: Int = 200, | |
scheduler: DispatchQueue = DispatchQueue.global(qos: .userInitiated), | |
worker: @escaping () -> Result<Output, Never>, | |
completion: @escaping (Output) -> ()) -> AnyCancellable { | |
Just(()) | |
.delay(for: .milliseconds(delay), scheduler: scheduler) | |
.flatMap { _ in Future { $0(worker()) } } | |
.receive(on: DispatchQueue.main) | |
//.handleEvents(receiveCancel: { print("Cancel event received") }) | |
.sink(receiveValue: completion) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment