Skip to content

Instantly share code, notes, and snippets.

@manmal
Forked from steipete/CombineHelper.swift
Created March 30, 2021 08:09
Show Gist options
  • Save manmal/db110801f556d48444fa556870d0d358 to your computer and use it in GitHub Desktop.
Save manmal/db110801f556d48444fa556870d0d358 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
func runDelayedInBackground<Output, DelayingScheduler: Scheduler, ReceivingScheduler: Scheduler>(
delay: Int = 200,
scheduler: DelayingScheduler,
receiveOn: ReceivingScheduler,
worker: @escaping () -> Result<Output, Never>,
completion: @escaping (Output) -> ()
) -> AnyCancellable {
Just(())
.delay(for: .milliseconds(delay), scheduler: scheduler)
.flatMap { _ in Future { $0(worker()) } }
.receive(on: receiveOn)
//.handleEvents(receiveCancel: { print("Cancel event received") })
.sink(receiveValue: completion)
}
func runDelayedInBackground<Output>(
delay: Int = 200,
worker: @escaping () -> Result<Output, Never>,
completion: @escaping (Output) -> ()
) -> AnyCancellable {
runDelayedInBackground(
delay: delay,
scheduler: DispatchQueue.global(qos: .userInitiated),
receiveOn: DispatchQueue.main,
worker: worker,
completion: completion
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment