how to stop a timer publisher?

Viewed 3300

I have been playing around a timer publisher for a while in playground. below is my code

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. :(
}

But i could not stop the timer by using both line 1 and line 2. What am i actually missing?

1 Answers

Your code executed before timer start when its not greater than 5 ... thats why those lines are not executing ...

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()

              }
}
Related