Recently, I have started working on an Android Project that stopped using Broadcast Receiver's in favor of "Listeners". Really, this implementation is using an observer pattern similar to this article (in my case, there is even .aidl involved).
What I am failing to understand is why. I have been taught that composition is better than inheritance. To me, a broadcast receiver is composition. It is a native Android feature, that everyone Android developer should be familiar with. So why, is there any reason that I should drop my Broadcast Receivers in favor of an observer pattern? Is this just a product of bad design on my teams part?
Update:
I did find a comment stating that this is to follow Single Responsiblity, however I am not sure I follow as any class implementing a listener is bound to have other responsibilties (for instance, activities, who are managing the UI lifecycle).
Observer pattern is used when there is one-to-many relationship between objects such as if one object is modified, its depenedent objects are to be notified automatically. Observer pattern falls under behavioral pattern category.
In general, the Observer pattern is used whenever you want to provide a mechanism for some modules in a system to subscribe to notifications from another part of a system without tightly coupling them together.
Consequences. The Observer pattern lets you vary subjects and observers independently. You can reuse subjects without reusing their observers, and vice versa. It lets you add observers without modifying the subject or other observers.
The Observer Design Pattern Solves Problems Like: How can a one-to-many dependency between objects be defined without making the objects tightly coupled? How to create a model to update all dependent objects when the state of one object changes?
Using BroadcastReceiver
s allows to decouple one component from another. A sender doesn't know anything about receivers of his message. It just sends broadcasts and doesn't care if it was received and handled. The same concept has an event bus (for example Otto). But global BroadcastReceiver
s have a small overhead because they are by their nature a cross-application facility. So if you need to send events only inside one application I would use LocalBroadcastManager or the event bus that I've pointed previously.
In case of using listeners (observers) components become tightly coupled because sender has a reference to the receiver and know about it's nature (what interface a listener implements) and must check if the listener is not null.
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