I'm going through the Head First Design Patterns book and doing my best to convert the code from their Java to C#. After the book discussed the observer pattern it mentioned that Java has classes/interfaces built in, as does .NET4. So I began researching how to use it properly and I have most of it figured out except for the Subscribe()
method.
If you look at the MSDN Article when you try subscribing an IObserver, the method returns an IDisposable. Why would that be necessary? Why not just implement a method that unsubcribes the IObserver based on a method argument? I researched the reason to use an IDisposable interface. I also read this but didn't quite understand the difference/what it was trying to tell me:
It returns a reference to an IDisposable interface. This enables observers to unsubscribe (that is, to stop receiving notifications) before the provider has finished sending them and called the subscriber's OnCompleted method.
Provides a mechanism for releasing unmanaged resources.
For implementing the IDisposable design pattern, the class which deals with unmanaged objects directly or indirectly should implement the IDisposable interface. And implement the method Dispose declared inside of the IDisposable interface.
The IObservable<T> interface represents the class that sends notifications (the provider); the IObserver<T> interface represents the class that receives them (the observer). T represents the class that provides the notification information.
The information that is required to cancel a subscription will vary depending upon how the event publisher manages subscriptions. The approach used for events--passing to the Remove
method the delegate previously passed to the Add
method--is kinda sorta workable, but has some significant deficiencies. Among them:
Having the event subscription method return an object that can be used to cancel the subscription avoids these problems. The biggest question then becomes what type of object should be used. Three choices come to mind:
Using a delegate would be a reasonable choice. It could be easily encapsulate whatever information was necessary to cancel a subscription without the user having to worry about what form that information might take. Using a delegate would entail the allocation of at least one extra heap object (for the delegate itself) and possibly two (the second being an object holding the unsubscription information). Using IDisposable
would be essentially the same as using a delegate, except that one would call Dispose
rather than Invoke
; in many cases, though, IDisposable
would have a slight advantage in terms of efficiency. Using some other interface would also be workable, but wouldn't really offer any advantage over using the existing IDisposable
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With