Implementing an EventBus in Android Using Reflection
This article explains the concept of an EventBus as an observer‑pattern based communication mechanism for Android components, illustrates it with a newspaper subscription analogy, and provides step‑by‑step Java implementation details—including registration, unregistration, and posting of events using reflection—plus integration tips within an Activity lifecycle.
The article introduces EventBus as a communication method between components in Android, describing it as an implementation of the observer pattern that allows event publishers to broadcast data to interested subscribers.
To make the concept intuitive, the author uses a newspaper subscription analogy: the EventBus acts like a newsstand owner who registers subscribers, delivers newspapers (events) when published, and removes subscribers when they unsubscribe.
Three core methods are defined for the EventBus class: regist (register a subscriber), unregist (unregister a subscriber), and post (publish an event).
The regist method uses Java reflection to scan a given Activity instance for methods whose names start with onEvent . Each such method’s parameter type becomes a key, and the method together with its instance is wrapped into a holder object and stored in a map.
The unregist method simply reverses the registration process, removing the subscriber’s entry from the map.
The post method receives an event object, determines its parameter type, looks up the corresponding list of subscriber holders in the map, and invokes each stored method in turn; if no subscriber exists for that type, the method does nothing.
To use the EventBus in an Android Activity, developers define methods prefixed with onEvent , register the EventBus in the Activity’s onResume lifecycle callback, unregister it in onPause , and call post wherever an event should be emitted, such as in a button click handler.
The article concludes by encouraging readers to experiment with the provided implementation, customize class names, keys, and method prefixes, and share any corrections or improvements.
Qunar Tech Salon
Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.