Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you stop an Observable.Timer()?

If an Observable is created using Observable.Timer(), how do you stop it?

let tmr = Observable.Timer(TimeSpan.Zero, TimeSpan.FromMilliseconds 1000.)
let subscription = tmr.Subscribe(myFunction)
// ...
subscription.Dispose()

Do you even need to stop it, or will it be garbage collected when all its subscribers have been disposed?

like image 733
John Reynolds Avatar asked Aug 21 '16 21:08

John Reynolds


People also ask

What is timer in RxJS?

RxJS timer() operator is a creation operator used to create an observable that starts emitting the values after the timeout, and the value will keep increasing after each call.


1 Answers

The timer doesn't even start "firing" until you subscribe to it (what you would call a "cold observable"). Moreover: it will start firing as many times as there are subscriptions to it. Try this:

let tmr = Observable.Timer(TimeSpan.Zero, TimeSpan.FromMilliseconds 1000.)
let subscription = tmr.Subscribe(printfn "A: %d")
Thread.Sleep 500
let subscription2 = tmr.Subscribe(printfn "B: %d")

This program will print A: 1, then B: 1, then A: 2, then B: 2, and so on - roughly every 500 milliseconds.

Consequently, the timer does stop "firing" as soon as the subscription is disposed. But only that particular timer, not all of them.

One way to think about your tmr object is as a "timer factory", not a "timer" as such.

like image 63
Fyodor Soikin Avatar answered Oct 21 '22 18:10

Fyodor Soikin