Can Observable.Timer() lead to memory leaks?

放肆的年华 提交于 2019-12-05 11:54:58

This is normal, and is a feature.

The semantics for Subscribe() are listen forever, or until Disposed() or OnCompleted(), or OnError(), which ever comes first.

You can keep a reference to the subscription, and even combine them with a CompositeDisposable, but the usual method of managing IObservable lifetime on an otherwise infinite operator (like Timer) is by using an operator that applies termination rules to another, like Take (take x values), TakeWhile (take values while f(x) returns true) or TakeUntil (take values until another sequence, y, emits a value or completes).

Running Rx operators won't be automatically GC'd unless they've completed. Timer / Interval, for example, both recursively schedule their next value using an IScheduler and the default instances of the various schedulers are all accessible via static properties of Scheduler. This makes the running operator always rooted and therefore unavailable for GC.

I don't agree with the answer. What you're essentially doing is redundant as you're using an infinite loop to create successive observables, hence the memory leak. Remove the while loop and just have one Observable.Timer or even better use an Observable.Interval. Just one instance then when you don't need it anymore call dispose on it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!