Maybe something like this can help?
private var timerSubscription: AnyCancellable?
func setupTimer(every interval: TimeInterval, repeats: Bool, onReceive: @escaping (() -> Void)) {
invalidateTimer()
timerSubscription = Timer
.publish(every: interval, on: .main, in: .common)
.autoconnect()
.sink { _ in
onReceive()
if !repeats {
self.invalidateTimer()
}
}
}
func invalidateTimer() {
timerSubscription?.cancel()
}
full service:
final class CombineTimerService {
// MARK: - Public Properties
var isCancelled: Bool {
return timerSubscription == nil
}
// MARK: - Private Properties
private var timerSubscription: AnyCancellable?
private var onReceive: (() -> Void)?
// MARK: - Public
func setupTimer(every interval: TimeInterval, repeats: Bool, onReceive: @escaping (() -> Void)) {
invalidateTimer()
self.onReceive = onReceive
timerSubscription = Timer
.publish(every: interval, on: .main, in: .common)
.autoconnect()
.sink { _ in
onReceive()
if !repeats {
self.invalidateTimer()
}
}
}
func invalidateTimer() {
timerSubscription?.cancel()
onReceive = nil
}
func fire() {
onReceive?()
}
}