Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger Timer.publish() right away?

Tags:

swift

combine

I created a timer via combine which emits Date and ignores errors using this code:

let timer: AnyPublisher<Date, Never> = Timer.publish(every: 5, on: .main, in: RunLoop.Mode.common)
  .autoconnect()
  .map { _ in Date() }
  .replaceError(with: Date())
  .eraseToAnyPublisher()

(I'm sure there are better ways than mapping and replacing the error, but for this example, I wanted to keep the type simple, AnyPublisher<Date, Never>.)

The timer fires correctly, but there is a delay between when the timer is created to when it fires the first time (i.e. it waits 5 seconds). With NSTimer, we can invoke timer.fire() to force it to fire immediately.

Is there an equivalent way to force a timer to post immediately when using Timer.publish()?


Alternatively, is there a way to merge Just(Date()) with the above Timer.publish so that it fires immediately and every 5 seconds, while still keeping the AnyPublisher<Date, Never> type?

like image 739
Senseful Avatar asked Feb 16 '26 12:02

Senseful


1 Answers

Also, there is an option using prepend

let delayPublisher = Timer.publish(every: 5, on: .main, in: .common)
  .autoconnect()
  .receive(on: RunLoop.main)
  .prepend(.now)
like image 181
Đỗ Long Thành Avatar answered Feb 21 '26 16:02

Đỗ Long Thành



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!