Skip to content

Instantly share code, notes, and snippets.

@steipete
Created March 30, 2021 07:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save steipete/58b1c14ed73686ac66337a7aef1c9854 to your computer and use it in GitHub Desktop.
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
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