Class
Publishers.Timer
public final class Timer<Scheduler: Combine.Scheduler>: ConnectablePublisher
A publisher that emits a scheduler's current time on a repeating interval.
This publisher is an alternative to Foundation's Timer.publisher
, with its primary
difference being that it allows you to use any scheduler for the timer, not just RunLoop
.
This is useful because the RunLoop
scheduler is not testable in the sense that if you want
to write tests against a publisher that makes use of Timer.publisher
you must explicitly
wait for time to pass in order to get emissions. This is likely to lead to fragile tests and
greatly bloat the time your tests take to execute.
It can be used much like Foundation's timer, except you specify a scheduler rather than a run loop:
Publishers.Timer(every: .seconds(1), scheduler: DispatchQueue.main)
.autoconnect()
.sink { print("Timer", $0) }
But more importantly, you can use it with TestScheduler
so that any Combine code you write
involving timers becomes more testable. This shows how we can easily simulate the idea of
moving time forward 1,000 seconds in a timer:
let scheduler = DispatchQueue.test
var output: [Int] = []
Publishers.Timer(every: 1, scheduler: scheduler)
.autoconnect()
.sink { _ in output.append(output.count) }
.store(in: &self.cancellables)
XCTAssertEqual(output, [])
scheduler.advance(by: 1)
XCTAssertEqual(output, [0])
scheduler.advance(by: 1)
XCTAssertEqual(output, [0, 1])
scheduler.advance(by: 1_000)
XCTAssertEqual(output, Array(0...1_001))
Relationships
Conforms To
ConnectablePublisher
Nested Type Aliases
Output
public typealias Output = Scheduler.SchedulerTimeType
Failure
public typealias Failure = Never
Initializers
init(every:tolerance:scheduler:options:)
public init(
every interval: Scheduler.SchedulerTimeType.Stride,
tolerance: Scheduler.SchedulerTimeType.Stride? = nil,
scheduler: Scheduler,
options: Scheduler.SchedulerOptions? = nil
)
Properties
interval
public let interval: Scheduler.SchedulerTimeType.Stride
options
public let options: Scheduler.SchedulerOptions?
scheduler
public let scheduler: Scheduler
tolerance
public let tolerance: Scheduler.SchedulerTimeType.Stride?
Methods
receive(subscriber:)
public func receive<Sub: Subscriber>(subscriber: Sub)
where Failure == Sub.Failure, Output == Sub.Input
connect()
public func connect() -> Cancellable