Timer publisher with initial fire now

Viewed 629

I have a simple timer publisher that fires every 10 seconds.

Timer
    .publish(every: 10, on: .main, in: .common)
    .autoconnect()
    .map { _ in ... }
    .sink(receiveValue: { [weak self] in
        ...
    })
    .store(in: &subscriptions)

However, the first time it fires is in 10 seconds from now. Can I set it to fire its first value now?

2 Answers

Alternatively to creating another publisher, you can simply prepend to your timer publisher:

Timer
    .publish(every: 10, on: .main, in: .common)
    .autoconnect()
    .prepend(Date())
    .map { _ in ... }
    .sink(receiveValue: { [weak self] in
        ...
    })
    .store(in: &subscriptions)

The above code has the same effect of publishing a value right away, and let the timer publish the other values.

I was able to achieve what I wanted, but I had to add another publisher:

let timer = Timer
                .publish(every: 10, on: .main, in: .common)
                .autoconnect()
let initial = Just(Date.init())

timer.merge(with: initial)
         .map { _ in ... }
         .sink(receiveValue: { [weak self] in
              ...
         })
         .store(in: &subscriptions)
Related