如何停止计时器发布者?

elk*_*ner 1 swift combine

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

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. :(
}
Run Code Online (Sandbox Code Playgroud)

但是我无法通过使用第 1 行和第 2 行来停止计时器。我实际上错过了什么?

use*_*632 8

您的代码在计时器开始之前执行,当它不大于 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()

              }
}
Run Code Online (Sandbox Code Playgroud)