Search code examples
design-patternsooplistenerobserver-pattern

How granular should you make your Observables/Listenables?


You have a pull-oriented Observable/Listenable which notifies Observers/Listeners when some state changes.

The state consists of more than one nugget of data, and some of your Observers/Listeners don't care about the whole state.

Do you generally prefer to notify all the Observers/Listeners anyway and allow them to ignore notifications when nothing they care about changed?

Or do you generally prefer a seperate Observable for each "nugget" of data so that your Observers/Listeners are guaranteed to only get notifications they need to respond to?

Does it depend on the situation?

Do you have any general thoughts on the granularity of your Observables/Listenables?


Solution

  • You're trading off maintenance costs against costs of delivery. If you have fine-grained Event definitions each observer gets only exactly what he needs, so you don't pay for the overhead of delivery to observers who are uninterested - but that saving costs because every new kind of nugget needs to be added to the system in some way.

    In Pub/Sub messaging systems where the delivery costs are relatively high (messages flowing over networks) one typically needs to pay careful attention to the topic deifintions. A carefully designed topic hierarchy is often useful. So we get patterns like

      sport
           football
                  england 
                        premier
                        champioship
                  scotland
                        spl
                  france
                        ...
           cricket
                  australia
                        ...
                  india
                  sri lanka
    

    Hence allowing subscriptions at various levels. You can subscribe to all sport or (as some folks might) right down to

        sport/football/england/championship/watford