开发者

Is using weak references in Observers a good idea?

I have implemented an Observable class that stores a list all the observers. Should this list contain weak references to the observers for preventing memory leaks?

What is comm开发者_运维技巧on practise?


Not necessarily, it depends on the context. Some observers may just want to do simple things like logging and such, and would prefer to be kept alive by the Observable object. Best thing to do is just to clearly document your choice, so that observers know whether or not they need to explicitly deregister themselves.


Off topic, if you are using Rx and not just the IObservable interface from .NET 4, you should map the Subscribe calls through to a private instance of Subject as it will handle thread safety and call order for you. You can then call On* on the subject instance.

On topic, it's typical that subscribers manage their own subscription. In the least this means disposing the Subscribe return value, but in Rx then subscription will usually be terminated by another operator (such as Take or TakeUntil).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜