Dot-Net
你如何停止 Observable.Timer()?
如果 Observable 是使用 創建的
Observable.Timer(),你如何停止它?let tmr = Observable.Timer(TimeSpan.Zero, TimeSpan.FromMilliseconds 1000.) let subscription = tmr.Subscribe(myFunction) // ... subscription.Dispose()你甚至需要停止它,還是在它的所有訂閱者都被釋放後它會被垃圾回收?
在您訂閱之前,計時器甚至不會開始“觸發”(您稱之為“冷可觀察”)。此外:它將開始觸發的次數與訂閱次數一樣多。嘗試這個:
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")該程序將列印
A: 1, thenB: 1, thenA: 2, thenB: 2等等 - 大約每 500 毫秒。因此,一旦訂閱被處理,計時器就會停止“觸發”。但只有那個特定的計時器,而不是全部。
考慮您的
tmr對象的一種方法是將其視為“計時器工廠”,而不是“計時器”。