Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to stop a timer publisher?

Tags:

swift

combine

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?

like image 621
elk_cloner Avatar asked Feb 20 '26 13:02

elk_cloner


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

              }
}
like image 73
Jawad Ali Avatar answered Feb 27 '26 10:02

Jawad Ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!