6

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?

elk_cloner
  • 2,049
  • 1
  • 12
  • 13

1 Answers1

19

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

              }
}
Jawad Ali
  • 13,556
  • 3
  • 32
  • 49