the publisher/subscriber pattern for loose coupling. • Enables central communication to decoupled classes with just a few lines of code – simplifying the code, removing dependencies, and speeding up app development
SomeOtherEvent is posted @Subscribe public void handleSomethingElse(SomeOtherEvent event) { doSomethingWith(event); } // This method will be called when a MessageEvent is posted (in the UI thread for Toast) @Subscribe(threadMode = ThreadMode.MAIN) public void onMessageEvent(MessageEvent event) { Toast.makeText(getActivity(), event.message, Toast.LENGTH_SHORT).show(); }
a certain type in memory when event posted sticky. • Used to post data even after subscriber unregistered and subscriber registered again • Used to cache data. E.g. sensor data, location data • Sticky event can be delivered to subscribers or queried explicitly.
stickyEvent = EventBus.getDefault().getStickyEvent(MessageEvent.class); // Better check that an event was actually posted before if(stickyEvent != null) { // "Consume" the sticky event EventBus.getDefault().removeStickyEvent(stickyEvent); // Now do something with it } MessageEvent stickyEvent = EventBus.getDefault().removeStickyEvent(MessageEvent.class); // Better check that an event was actually posted before if(stickyEvent != null) { // Now do something with it }
ThreadMode: BACKGROUND • ThreadMode: ASYNC // Called in the same thread (default) // ThreadMode is optional here @Subscribe(threadMode = ThreadMode.POSTING); // Called in Android UI's main thread @Subscribe(threadMode = ThreadMode.MAIN); // Called in the background thread @Subscribe(threadMode = ThreadMode.BACKGROUND); // Called in a separate thread @Subscribe(threadMode = ThreadMode.ASYNC);
will receive events before others with a lower priority. Default priority is 0. In different delivery thread priority of delivery will not affect. @Subscribe(priority = 1); public void onEvent(MessageEvent event) { … }
Cancelling is restricted to event handling methods running in posting thread ThreadMode.POST (Default). EventBus.getDefault().cancelEventDelivery(event) ;
the @Subscribe annotation to your subscriber methods • Thread delivery support: Main(UI), Background, Async • Event & Subscriber inheritance : The OOPs apply to event and subscriber • Zero configuration: Immediately using a default EventBus instance • Configurable: Adjust its behavior using the builder pattern.
receivers • Performs well with Activities, Fragments, and background threads • Avoids complex and error-prone dependencies and life cycle issues • Is fast; specifically optimized for high performance