.netf#system.reactive

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?


Solution

  • 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.