如何停止计时器发布者?

how to stop a timer publisher?

我在操场上玩了一段时间的定时器发布器。下面是我的代码

let timer = Timer
    .publish(every: 1.0, on: .main, in: .common)
.autoconnect()

var counter = 0
let subscriber = timer
    .map({ (date) -> Void in
        counter += 1
    })
    .sink { _ in

        print("I am printing the counter \(counter)")
}

if counter > 5 {
    timer.upstream.connect().cancel() //1.nothing happened
    subscriber.cancel() //2. nothing happened too. :(
}

但是我无法同时使用第 1 行和第 2 行来停止计时器。 我到底错过了什么?

你的代码在计时器启动之前执行,当它不大于 5 时......这就是为什么这些行没有执行......

let timer = Timer
    .publish(every: 1.0, on: .main, in: .common)
.autoconnect()

var counter = 0
let subscriber = timer
    .map({ (date) -> Void in
        counter += 1
    })
    .sink { _ in

        print("I am printing the counter \(counter)")
        if counter >= 5 {
                  print("greater than 5")
                  timer.upstream.connect().cancel()

              }
}