Skip to content

Instantly share code, notes, and snippets.

@jayrhynas
Created March 7, 2022 17:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jayrhynas/a8d0642728020b5721ce2d3e7174801d to your computer and use it in GitHub Desktop.
Save jayrhynas/a8d0642728020b5721ce2d3e7174801d to your computer and use it in GitHub Desktop.
import Foundation
import Combine
extension Timer {
static func publish(at date: Date, tolerance: TimeInterval? = nil, on runLoop: RunLoop, in mode: RunLoop.Mode, options: RunLoop.SchedulerOptions? = nil) -> AnyPublisher<Date, Never> {
let subject = PassthroughSubject<Date, Never>()
let timer = Timer(fire: date, interval: 0, repeats: false) { _ in
subject.send(Date())
subject.send(completion: .finished)
}
if let tolerance = tolerance {
timer.tolerance = tolerance
}
runLoop.add(timer, forMode: mode)
return subject.handleEvents(receiveCancel: { [weak timer] in
timer?.invalidate()
}).eraseToAnyPublisher()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment