BusUtils is an efficient event bus that manages event subscriptions and dispatching through several internal mechanisms:
1. Registration
When an object is registered via BusUtils.register(Object bus), the library:
- Maps the object's class name to a thread-safe
CopyOnWriteArraySet of subscribers in mClassName_BusesMap. - Processes any existing sticky events via
processSticky.
2. Event Posting
When BusUtils.post(String tag, Object arg) is called:
- It looks up the
BusInfo associated with the tag in mTag_BusInfoMap. - It retrieves the cached
Method instance for the subscriber's function. - It dispatches the event to the appropriate thread pool based on the configured
threadMode.
3. Thread Modes
BusUtils supports multiple execution contexts via the threadMode attribute:
MAIN: Executes on the UI thread using Utils.runOnUiThread.IO: Executes on the IO thread pool.CPU: Executes on the CPU thread pool.CACHED: Executes on the cached thread pool.SINGLE: Executes on a single background thread pool.- Default: Executes on the current thread.
4. Unregistration
BusUtils.unregister(Object bus) removes the object from the mClassName_BusesMap to prevent memory leaks and further event dispatching to that instance.