Reputation: 2586
Although it is possible to attach an observer to multiple providers, the recommended pattern is to attach an
IObserver
instance to only oneIObservable
instance.
taken from Observer Design Pattern Best Practices.
I don't see any obvious reason why it is adviced to assign an observer to only one observable. In fact I would like to do exactly this to constantly refresh a statistic that depends on multiple changing values.
It seems to me like msdn is suggesting that i create an instance of a dedicated observer-class for every single value that i want to observe, whereas my intuition would be to make my statistics class assign to the IObservables directly.
What would be the "proper" way to implement this and what are the reasons why i should NOT assign my class to multiple observables?
Upvotes: 2
Views: 940
Reputation: 61993
As far as I can tell, there is no good reason for this "best practice".
I can see only one scenario in which you might want to do this, but it certainly does not constitute a reason to call this a "best practice".
Suppose you need to know who the observable issuing the notification is, and suppose that the observable does not identify itself via the value
parameter of OnNext()
. Then, you have to instantiate a different observer per observable, and pass the observable as a constructor parameter to the observer (*1).
In your case you do not need to know who the observable issuing the notification is, so this scenario does not apply to you.
(*1) As a matter of fact, it is precisely in order to save you from having to instantiate unnecessary observers that many frameworks mandate that any notification should include a reference to the originator of the notification.
Upvotes: 2