### Install Default EventBus Instance Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/eventbus-builder.md Install the current builder configuration as the process-wide default EventBus. This should be called exactly once during application initialization. ```java public class MyApp extends Application { @Override public void onCreate() { super.onCreate(); EventBus.builder() .logSubscriberExceptions(true) .strictMethodVerification(true) .installDefaultEventBus(); } } ``` -------------------------------- ### Generated SubscriberInfo Implementation Example Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/annotation-processor.md An example of a generated SubscriberInfo class extending AbstractSubscriberInfo. It requires specific constructor parameters for initialization. ```java public class MyFragment_SubscriberInfo extends AbstractSubscriberInfo { public MyFragment_SubscriberInfo() { super(MyFragment.class, null, true, false); } @Override public SubscriberMethod[] getSubscriberMethods() { // Return subscriber methods } } ``` -------------------------------- ### Complete EventBus Working Example Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/quick-reference.md This example shows how to define events, register an activity with EventBus, post events for asynchronous operations, and subscribe to events on the main thread for UI updates. It also includes basic error handling. ```java // Event definition public class FetchUserEvent { public final int userId; public FetchUserEvent(int userId) { this.userId = userId; } } public class UserFetchedEvent { public final User user; public UserFetchedEvent(User user) { this.user = user; } } // Activity public class UserActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user); } @Override protected void onStart() { super.onStart(); EventBus.getDefault().register(this); } @Override protected void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } public void loadUser(int userId) { // Post event to trigger async loading AsyncExecutor.create().execute(() -> { User user = fetchUserFromApi(userId); EventBus.getDefault().post(new UserFetchedEvent(user)); }); } @Subscribe(threadMode = ThreadMode.MAIN) public void onUserFetched(UserFetchedEvent event) { // Update UI on main thread displayUser(event.user); } @Subscribe(threadMode = ThreadMode.MAIN) public void onError(ThrowableFailureEvent event) { // Show error Toast.makeText(this, "Error loading user", Toast.LENGTH_SHORT).show(); } } ``` -------------------------------- ### Install Custom Default EventBus Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/quick-reference.md Configure and install a custom EventBus as the default instance for the application. This is typically done once in the Application class's onCreate() method. ```java // In Application.onCreate() EventBus.builder() .throwSubscriberException(BuildConfig.DEBUG) .strictMethodVerification(true) .installDefaultEventBus(); ``` -------------------------------- ### Install Default EventBus Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/README.md Build a custom EventBus and set it as the default instance. This replaces the default singleton. ```java builder.installDefaultEventBus(); ``` -------------------------------- ### Example: Subscribe with BACKGROUND ThreadMode Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/annotations-and-threadmode.md Example of an event handler method that runs on a background thread. Suitable for I/O operations or intensive tasks. ```java @Subscribe(threadMode = ThreadMode.BACKGROUND) public void onNetworkEvent(NetworkEvent event) { // Runs on background thread, safe for I/O fetchData(event.url); } ``` -------------------------------- ### Basic EventBus Setup Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/eventbus-builder.md Instantiate a basic EventBus with event inheritance enabled. Register a subscriber and post an event to demonstrate usage. ```java EventBus myBus = EventBus.builder() .eventInheritance(true) .build(); myBus.register(subscriber); myBus.post(new MyEvent()); ``` -------------------------------- ### Example: Multi-Handler Event Subscription Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/README.md Demonstrates how multiple subscriber methods can handle the same event, showcasing different ThreadModes and priorities. ```java public class MySubscribers { @Subscribe(threadMode = ThreadMode.MAIN) public void onEventMain(MyEvent event) { // Handle on main thread } @Subscribe(threadMode = ThreadMode.BACKGROUND, priority = 1) public void onEventBackground(MyEvent event) { // Handle in background thread with priority 1 } @Subscribe(sticky = true, threadMode = ThreadMode.ASYNC) public void onStickyEventAsync(MyStickyEvent event) { // Handle sticky event asynchronously } } ``` -------------------------------- ### Example: Subscribe with MAIN ThreadMode Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/annotations-and-threadmode.md Example of an event handler method that runs on Android's main thread (UI thread). Use this for updating the UI. ```java @Subscribe(threadMode = ThreadMode.MAIN) public void onMessageEvent(MessageEvent event) { // Runs on main thread, safe to update UI textView.setText(event.message); } ``` -------------------------------- ### installDefaultEventBus() Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/eventbus-builder.md Installs this builder's configuration as the process-wide default EventBus instance, accessible via EventBus.getDefault(). This method must be called exactly once, before the first access to EventBus.getDefault(). ```APIDOC ## installDefaultEventBus() ### Description Installs this builder's configuration as the process-wide default EventBus instance, accessible via `EventBus.getDefault()`. Must be called exactly once, before the first access to `EventBus.getDefault()`. ### Return - **EventBus** - The newly installed default instance ### Throws - **EventBusException** - If a default instance already exists (called more than once) ### Usage Pattern Call in application initialization code (e.g., `onCreate()` in Application class on Android). ### Request Example ```java public class MyApp extends Application { @Override public void onCreate() { super.onCreate(); EventBus.builder() .logSubscriberExceptions(true) .strictMethodVerification(true) .installDefaultEventBus(); } } ``` ``` -------------------------------- ### EventBus ThreadMode Examples Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/quick-reference.md Illustrates the usage of different `threadMode` options for event handlers, each suited for specific scenarios. ```java // Fastest, immediate execution @Subscribe(threadMode = ThreadMode.POSTING) public void onEvent(MyEvent event) { } ``` ```java // Safe for UI updates on Android @Subscribe(threadMode = ThreadMode.MAIN) public void onUIEvent(UIEvent event) { } ``` ```java // Non-blocking main thread operation @Subscribe(threadMode = ThreadMode.MAIN_ORDERED) public void onOrderedEvent(OrderedEvent event) { } ``` ```java // Safe for I/O operations @Subscribe(threadMode = ThreadMode.BACKGROUND) public void onIOEvent(IOEvent event) { } ``` ```java // Concurrent background processing @Subscribe(threadMode = ThreadMode.ASYNC) public void onAsyncEvent(AsyncEvent event) { } ``` -------------------------------- ### Annotation Processor Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/README.md Guide to using the EventBus annotation processor for generating compile-time indexes to improve performance. ```APIDOC ## Annotation Processor ### Purpose - Generates compile-time indexes for subscribers to enhance performance by avoiding reflection. ### Setup - **Dependencies**: Add Gradle/Maven dependencies for the annotation processor. - **Rebuild**: Rebuild the project after adding dependencies. - **Registration**: Ensure generated indexes are registered with EventBus. ### Generated Code - **Index Classes**: `SubscriberInfoIndex` implementations. - **SubscriberInfo Classes**: Metadata for subscribers. - **SubscriberMethod**: Class holding subscriber method details. ### Configuration - **ProGuard/R8**: Includes necessary configurations for code shrinking and obfuscation. - **Multi-module Projects**: Setup instructions for multi-module environments. ### Troubleshooting - Common issues like index not being generated or found, and ProGuard/R8 conflicts. ``` -------------------------------- ### Modular Project Setup: Registering Generated Indexes Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/annotation-processor.md In a multi-module application, register the generated index classes (e.g., `AppIndex`, `FeatureIndex`) with EventBus during application startup. This is done within the `Application` class's `onCreate()` method. ```java public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); EventBus.builder() .addIndex(new AppIndex()) .addIndex(new FeatureIndex()) .installDefaultEventBus(); } } ``` -------------------------------- ### ThreadMode.MAIN Example Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/annotations-and-threadmode.md Subscribers execute on the main (UI) thread. On Android, if already on the main thread, it executes immediately; otherwise, it's queued. Non-Android platforms treat this as POSTING. Use for UI updates. ```java @Subscribe(threadMode = ThreadMode.MAIN) public void onDataReady(DataReadyEvent event) { // Safe to update UI directly listView.setAdapter(event.getAdapter()); progressBar.setVisibility(View.GONE); } ``` -------------------------------- ### EventBus Repository File Structure Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/INDEX.md Overview of the EventBus project's directory structure, including source files, annotation processor, and examples. ```tree EventBus/ ├── src/org/greenrobot/eventbus/ │ ├── EventBus.java — Main class │ ├── EventBusBuilder.java — Builder │ ├── Subscribe.java — @Subscribe annotation │ ├── ThreadMode.java — ThreadMode enum │ ├── EventBusException.java — Exception │ ├── NoSubscriberEvent.java — No subscriber event │ ├── SubscriberExceptionEvent.java — Exception event │ ├── Logger.java — Logger interface │ ├── MainThreadSupport.java — Main thread interface │ ├── Poster.java — Poster interface │ ├── SubscriberMethod.java — Method metadata │ ├── SubscriberMethodFinder.java — Method finder │ ├── Subscription.java — Subscription │ ├── BackgroundPoster.java — Background thread │ ├── AsyncPoster.java — Async thread │ ├── PendingPost.java — Pending event │ ├── PendingPostQueue.java — Event queue │ ├── PostingThreadState.java — Thread state │ ├── android/ — Android-specific │ │ ├── AndroidComponents.java │ │ └── AndroidDependenciesDetector.java │ ├── meta/ — Annotation processor │ │ ├── SubscriberInfoIndex.java │ │ ├── SubscriberInfo.java │ │ ├── AbstractSubscriberInfo.java │ │ ├── SimpleSubscriberInfo.java │ │ └── SubscriberMethodInfo.java │ └── util/ — Utilities │ ├── AsyncExecutor.java │ ├── ThrowableFailureEvent.java │ ├── HasExecutionScope.java │ └── ExceptionToResourceMapping.java ├── EventBusAnnotationProcessor/ — Annotation processor source └── Examples/ — Example projects ``` -------------------------------- ### Generated Index Class Example Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/annotation-processor.md This Java snippet represents a generated index class, typically found in `app/build/generated/source/apt/`. It implements `SubscriberInfoIndex` and provides a lookup for subscriber information, mapping subscriber classes to their respective `SubscriberInfo`. ```java // Generated as: app/build/generated/source/apt/.../AppIndex.java public class AppIndex implements SubscriberInfoIndex { @Override public SubscriberInfo getSubscriberInfo(Class subscriberClass) { if (subscriberClass == MainActivity.class) { return new MainActivity_SubscriberInfo(); } return null; } } ``` -------------------------------- ### ThreadMode.POSTING Example Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/annotations-and-threadmode.md Subscribers execute directly in the posting thread. This is the default and fastest option, suitable for quick operations. Caution: Must return quickly to avoid blocking the posting thread, especially on Android's main thread. ```java @Subscribe(threadMode = ThreadMode.POSTING) public void onEvent(MyEvent event) { // Executes immediately in posting thread // Must be fast - blocks caller if on main thread updateLocalState(event); } ``` -------------------------------- ### Modular Project Setup: Annotation Processor Dependency Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/annotation-processor.md Add the EventBus annotation processor as a dependency in the `build.gradle` file for each module in a multi-module Android application. This enables the annotation processor to generate necessary index classes. ```gradle dependencies { annotationProcessor("org.greenrobot:eventbus-annotation-processor:3.3.1") } ``` -------------------------------- ### Handling NoSubscriberEvent Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/events-and-errors.md Example of subscribing to NoSubscriberEvent to log events that were not delivered to any subscriber. This is useful for debugging. ```java @Subscribe public void onNoSubscriberEvent(NoSubscriberEvent event) { Log.w("EventBus", "No subscribers for " + event.originalEvent.getClass().getName()); } ``` -------------------------------- ### ThreadMode.BACKGROUND Example Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/annotations-and-threadmode.md Subscribers execute on a background thread. If posted from the main thread, it's queued on a single background thread; otherwise, it executes immediately in the posting thread. Events from the main thread are delivered sequentially. Use for I/O or database operations. ```java @Subscribe(threadMode = ThreadMode.BACKGROUND) public void onDataRequest(DataRequestEvent event) { // Safe to perform blocking I/O, database operations Data data = fetchFromDatabase(event.id); EventBus.getDefault().post(new DataReadyEvent(data)); } ``` -------------------------------- ### Get Subscriber Info Method Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/types-and-interfaces.md Looks up and returns SubscriberInfo for a given class. This method is crucial for EventBus during subscriber registration to avoid reflection. ```java SubscriberInfo getSubscriberInfo(Class subscriberClass) ``` -------------------------------- ### ThreadMode.MAIN_ORDERED Example Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/annotations-and-threadmode.md Subscribers always execute on the main thread and are always queued, ensuring the posting call never blocks, even when called from the main thread. Use for guaranteed non-blocking main thread operations. ```java @Subscribe(threadMode = ThreadMode.MAIN_ORDERED) public void onEvent(MyEvent event) { // Always queued, posting call never blocks updateUI(event); } ``` -------------------------------- ### @Subscribe Annotation and ThreadMode Enum Reference Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/README.md Detailed guide to the @Subscribe annotation properties and the ThreadMode enum, explaining event handling and threading options. ```APIDOC ## @Subscribe Annotation and ThreadMode Enum ### Description Defines how event handlers are annotated and how threading is managed for event delivery. ### @Subscribe Annotation Properties - **`threadMode`** - **Description**: Specifies the `ThreadMode` for event delivery. Options include `POSTING`, `MAIN`, `MAIN_ORDERED`, `BACKGROUND`, `ASYNC`. - **Default**: `POSTING` - **`sticky`** - **Description**: If `true`, the event will be delivered as a sticky event, meaning it will be stored and delivered to new subscribers that subscribe after the event was posted. - **Default**: `false` - **`priority`** - **Description**: An integer value that determines the order of execution for subscribers handling the same event. Higher values are executed first. - **Default**: `0` ### Method Requirements - Event handler methods must be `public`. - Event handler methods must return `void`. - Event handler methods must accept exactly one parameter. ### ThreadMode Enum - **`POSTING`** - **Description**: Event handlers are executed in the same thread that posted the event. This is the default `ThreadMode`. - **Use Cases**: Immediate processing, simple event handling. - **Cautions**: Avoid long-running operations to prevent blocking the posting thread. - **`MAIN`** - **Description**: Event handlers are executed on the Android main thread (UI thread). If the event is posted from the main thread, the handler is executed immediately; otherwise, it's posted to the main thread's message queue. - **Use Cases**: UI updates, interacting with Android UI components. - **Cautions**: Long-running operations will block the main thread. - **`MAIN_ORDERED`** - **Description**: Event handlers are executed on the Android main thread in the order they were received. Events are always queued, even if posted from the main thread. - **Use Cases**: Ensuring ordered UI updates or operations on the main thread. - **Cautions**: Can lead to deadlocks if not used carefully; long-running operations block the main thread. - **`BACKGROUND`** - **Description**: Event handlers are executed in a background thread. If the event is posted from a background thread, the handler is executed immediately in that thread; otherwise, it's posted to a shared background thread pool. - **Use Cases**: Performing I/O operations or other tasks that should not block the main thread. - **Cautions**: Subscribers should not directly update UI elements from this thread. - **`ASYNC`** - **Description**: Event handlers are executed in a separate thread pool managed by EventBus. This ensures that handlers do not block each other or the posting thread. - **Use Cases**: Independent, potentially long-running tasks. - **Cautions**: Subscribers should not directly update UI elements from this thread. ``` -------------------------------- ### Handling Subscriber Exceptions with SubscriberExceptionEvent Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/events-and-errors.md Example of how to subscribe to SubscriberExceptionEvent to handle exceptions thrown by other subscribers. This allows for centralized logging and conditional error dialogs based on the exception type. ```java @Subscribe public void onSubscriberException(SubscriberExceptionEvent event) { Log.e("EventBus", "Exception in " + event.causingSubscriber.getClass().getSimpleName() + " while handling " + event.causingEvent.getClass().getSimpleName(), event.throwable); if (event.throwable instanceof IOException) { showNetworkErrorDialog(); } else if (event.throwable instanceof IllegalArgumentException) { showInvalidDataDialog(); } } ``` -------------------------------- ### Subscribe to Events on Main Thread Source: https://github.com/greenrobot/eventbus/blob/master/README.md Declare a subscribing method annotated with @Subscribe and specify the thread mode. This example subscribes to MessageEvent on the main thread. ```java @Subscribe(threadMode = ThreadMode.MAIN) public void onMessageEvent(MessageEvent event) { // Do something } ``` -------------------------------- ### Register Generated Index for Default EventBus Instance Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/annotation-processor.md In your Application class, register the generated index when installing the default EventBus instance to ensure it's used from startup. ```java public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); EventBus.builder() .addIndex(new MyAppIndex()) .installDefaultEventBus(); } } ``` -------------------------------- ### ThreadMode.ASYNC Example Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/annotations-and-threadmode.md Subscribers execute in a separate thread pool, independent of the posting and main threads. Each event posting is non-blocking, and multiple handlers can run concurrently. Use for long-running operations or heavy computation. Caution: Can create many threads if many async events are posted rapidly. ```java @Subscribe(threadMode = ThreadMode.ASYNC) public void onDownloadRequest(DownloadRequestEvent event) { // Runs in thread pool, doesn't block caller // Multiple downloads can happen concurrently downloadFile(event.url); } ``` -------------------------------- ### Get Subscriber Methods Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/types-and-interfaces.md Returns an array of SubscriberMethod objects, representing all subscriber methods found within the described class. This is a key method of the SubscriberInfo interface. ```java SubscriberMethod[] getSubscriberMethods() ``` -------------------------------- ### Good Event Class: Simple Immutable Event Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/quick-reference.md Create simple, immutable event classes to represent specific occurrences. This example shows a UserLoginEvent with a final User object. ```java // Simple, immutable event public class UserLoginEvent { public final User user; public UserLoginEvent(User user) { this.user = user; } } ``` -------------------------------- ### Create EventBus Instances Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/eventbus.md Demonstrates creating a custom EventBus instance and accessing the default process-wide singleton instance. Each instance maintains separate subscriptions. ```java public EventBus() ``` ```java // Create a custom EventBus instance EventBus customBus = new EventBus(); // Access the process-wide default instance EventBus defaultBus = EventBus.getDefault(); ``` -------------------------------- ### build() Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/eventbus-builder.md Creates a new EventBus instance with the current configuration. This method does not affect the default singleton instance. ```APIDOC ## build() ### Description Creates a new EventBus instance with the current configuration. Does not affect the default singleton instance. ### Return - **EventBus** - A new configured EventBus instance ### Request Example ```java EventBus customBus = EventBus.builder() .logSubscriberExceptions(false) .eventInheritance(false) .build(); ``` ``` -------------------------------- ### Get Subscriber Class Method Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/types-and-interfaces.md Retrieves the subscriber class associated with this metadata. This method is part of the SubscriberInfo interface. ```java Class getSubscriberClass() ``` -------------------------------- ### Get Default EventBus Instance Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/README.md Access the singleton instance of EventBus. This is the primary way to interact with the event bus. ```java EventBus.getDefault() ``` -------------------------------- ### EventBus Registration With Annotation Processor Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/annotation-processor.md This snippet demonstrates EventBus registration using the annotation processor. It achieves significantly faster registration times (0.1-1ms) by using a compiled index for direct lookup, eliminating reflection. ```java EventBus.builder() .addIndex(new MyAppIndex()) .installDefaultEventBus(); EventBus.getDefault().register(subscriber); // Takes ~0.1-1ms (compiled lookup) // Direct index lookup, no reflection ``` -------------------------------- ### Rebuild Project (Gradle) Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/annotation-processor.md After adding the annotation processor dependency, clean and rebuild your project using Gradle to trigger the index generation. ```bash # Gradle ./gradlew clean build ``` -------------------------------- ### Get EventBus Logger Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/eventbus.md Retrieves the logger instance used internally by the EventBus for logging operations. Useful for custom logging configurations. ```java public Logger getLogger() ``` ```java Logger logger = EventBus.getDefault().getLogger(); logger.log(Level.INFO, "Custom log message"); ``` -------------------------------- ### build() Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/async-executor.md Builds and returns a new `AsyncExecutor` instance with the configured settings and a null execution scope. ```APIDOC ## build() ```java public AsyncExecutor build() ``` Builds the executor with default execution scope (`null`). | Return | Type | Description | |--------|------|-------------| | — | `AsyncExecutor` | A new executor instance | **Example:** ```java AsyncExecutor executor = AsyncExecutor.builder() .threadPool(Executors.newFixedThreadPool(4)) .build(); ``` ``` -------------------------------- ### Get Super Subscriber Info Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/types-and-interfaces.md Retrieves the SubscriberInfo for the superclass, if one exists. This allows for hierarchical lookup of subscribers. Part of the SubscriberInfo interface. ```java SubscriberInfo getSuperSubscriberInfo() ``` -------------------------------- ### create() - Static Factory Method Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/async-executor.md Creates an AsyncExecutor with default configuration, using EventBus.getDefault(), a cached thread pool, and ThrowableFailureEvent for failures. ```APIDOC ## create() ```java public static AsyncExecutor create() ``` Creates an `AsyncExecutor` with default configuration: - Uses `EventBus.getDefault()` - Thread pool: `Executors.newCachedThreadPool()` - Failure event type: `ThrowableFailureEvent` | Return | Type | Description | |--------|------|-------------| | — | `AsyncExecutor` | A new executor with default settings | **Example:** ```java AsyncExecutor executor = AsyncExecutor.create(); executor.execute(() -> { downloadFile("http://example.com/file.zip"); }); ``` ``` -------------------------------- ### Registering Multiple Indexes for Modular Projects Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/annotation-processor.md Use this when your project is modular and spans multiple packages to ensure all indexes are included. ```java EventBus eventBus = EventBus.builder() .addIndex(new MainAppIndex()) .addIndex(new ModuleAIndex()) .addIndex(new ModuleBIndex()) .build(); ``` -------------------------------- ### Get EventBus Logger Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/README.md Retrieve the logger instance used by EventBus. This allows for custom logging configurations or integration with existing logging frameworks. ```java eventBus.getLogger(); ``` -------------------------------- ### createPoster() Method Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/types-and-interfaces.md Creates a Poster implementation for queuing events to the main thread. Requires an EventBus instance. ```java Poster createPoster(EventBus eventBus) ``` -------------------------------- ### Build Custom EventBus Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/README.md Finalize the configuration and build a custom EventBus instance. ```java EventBus customBus = builder.build(); ``` -------------------------------- ### Get Default EventBus Singleton Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/eventbus.md Retrieves the process-wide default EventBus singleton instance. This method is thread-safe and idempotent, creating the instance on first access. ```java public static EventBus getDefault() ``` ```java EventBus bus = EventBus.getDefault(); bus.register(this); ``` -------------------------------- ### EventBus Registration with Fallback to Reflection Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/annotation-processor.md This demonstrates the standard EventBus registration method, which automatically falls back to using reflection if a generated index is not found or registered. This ensures functionality but may be slower. ```java // This still works if index is missing, just slower EventBus.getDefault().register(subscriber); ``` -------------------------------- ### Choose Appropriate ThreadMode for Subscribers Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/quick-reference.md Select the most suitable thread mode for your subscriber methods. POSTING is the fastest as it executes directly in the posting thread. Use BACKGROUND or ASYNC only when necessary. ```java // Fastest - direct execution in posting thread @Subscribe(threadMode = ThreadMode.POSTING) ``` ```java // Slower - requires thread switch @Subscribe(threadMode = ThreadMode.BACKGROUND) ``` ```java // Use ASYNC only if really needed @Subscribe(threadMode = ThreadMode.ASYNC) ``` -------------------------------- ### Get a Sticky Event from the EventBus Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/eventbus.md Retrieves the most recent sticky event for a given type without removing it from the bus. Returns null if no sticky event of the specified type is found. ```java public T getStickyEvent(Class eventType) ``` ```java CurrentUserEvent event = EventBus.getDefault().getStickyEvent(CurrentUserEvent.class); if (event != null) { updateUI(event.getUser()); } ``` -------------------------------- ### Get the Last Sticky Event Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/README.md Retrieve the last sticky event of a specific type. This is useful for scenarios where a subscriber needs to access the most recent sticky event upon registration. ```java eventBus.getStickyEvent(EventType.class); ``` -------------------------------- ### Registering Multiple Indexes Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/annotation-processor.md Demonstrates how to configure EventBus with multiple indexes for modular applications, allowing for better organization and management of subscriber information across different modules. ```APIDOC ## Registering Multiple Indexes For modular projects with multiple packages: ```java EventBus eventBus = EventBus.builder() .addIndex(new MainAppIndex()) .addIndex(new ModuleAIndex()) .addIndex(new ModuleBIndex()) .build(); ``` ``` -------------------------------- ### Registering Subscriber Index with EventBus Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/annotation-processor.md Ensure the generated index class is registered with EventBus before it is used. This is crucial for performance and proper event delivery. Call this during your application's setup. ```java // Make sure to register index BEFORE using EventBus EventBus.builder() .addIndex(new MyAppIndex()) // Add this .installDefaultEventBus(); ``` -------------------------------- ### Unit Test EventBus with TestSubscriber Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/quick-reference.md Demonstrates how to unit test EventBus functionality using a custom TestSubscriber. Set up a test EventBus instance and register the subscriber. ```java public class MyServiceTest { private EventBus testBus; private TestSubscriber subscriber; @Before public void setUp() { testBus = new EventBus(); subscriber = new TestSubscriber(); testBus.register(subscriber); } @Test public void testEventPosting() { MyEvent event = new MyEvent("test"); testBus.post(event); assertEquals(event, subscriber.receivedEvent); } } public class TestSubscriber { public MyEvent receivedEvent; @Subscribe public void onEvent(MyEvent event) { this.receivedEvent = event; } } ``` -------------------------------- ### Rebuild Project (Maven) Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/annotation-processor.md Clean and compile your Maven project to ensure the annotation processor runs and generates the subscriber index. ```bash # Maven mvn clean compile ``` -------------------------------- ### Provide Custom ExecutorService Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/eventbus-builder.md Provides a custom ExecutorService for async and background thread operations. By default, uses a cached thread pool. The provided executor must not get stuck or deadlock. ```java public EventBusBuilder executorService(ExecutorService executorService) ``` ```java ExecutorService executor = Executors.newFixedThreadPool(4); EventBus bus = EventBus.builder() .executorService(executor) .build(); ``` -------------------------------- ### Create a Custom EventBus Instance Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/README.md Use the builder pattern to create a custom EventBus instance with specific configurations. This allows for fine-grained control over the event bus behavior. ```java EventBus.builder() ``` -------------------------------- ### Create AsyncExecutor with Defaults Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/async-executor.md Creates an `AsyncExecutor` instance using default configurations, including `EventBus.getDefault()`, a cached thread pool, and `ThrowableFailureEvent` for failures. ```java AsyncExecutor executor = AsyncExecutor.create(); executor.execute(() -> { downloadFile("http://example.com/file.zip"); }); ``` -------------------------------- ### buildForScope(Object) Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/async-executor.md Builds and returns a new `AsyncExecutor` instance with the configured settings and a specified execution scope. ```APIDOC ## buildForScope(Object executionContext) ```java public AsyncExecutor buildForScope(Object executionContext) ``` Builds the executor with a specific execution scope. The scope is set on failure events that implement `HasExecutionScope`. | Parameter | Type | Description | |-----------|------|-------------| | executionContext | `Object` | The execution scope (e.g., a Fragment, Activity, or request context) | | Return | Type | Description | |--------|------|-------------| | — | `AsyncExecutor` | A new executor instance with the scope set | **Use case:** Distinguishing which component context failed (e.g., Fragment A vs Fragment B both posting failures). **Example:** ```java // In a Fragment or Activity AsyncExecutor executor = AsyncExecutor.builder() .buildForScope(this); // Set this Fragment/Activity as scope executor.execute(() -> { // If exception occurs, failure event has getExecutionScope() == this loadData(); }); // In handler @Subscribe public void onTaskFailure(ThrowableFailureEvent event) { if (event.getExecutionScope() instanceof MyFragment) { MyFragment fragment = (MyFragment) event.getExecutionScope(); fragment.showError(event.getThrowable()); } } ``` ``` -------------------------------- ### AbstractSubscriberInfo Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/annotation-processor.md Serves as the base class for generated SubscriberInfo implementations. It provides default implementations and is extended by generated classes, which then override methods like getSubscriberMethods. ```APIDOC ## AbstractSubscriberInfo Base class for generated `SubscriberInfo` implementations: ```java public abstract class AbstractSubscriberInfo implements SubscriberInfo ``` Provides default implementations. Generated classes extend this: ```java public class MyFragment_SubscriberInfo extends AbstractSubscriberInfo { public MyFragment_SubscriberInfo() { super(MyFragment.class, null, true, false); } @Override public SubscriberMethod[] getSubscriberMethods() { // Return subscriber methods } } ``` **Constructor parameters:** 1. Subscriber class 2. Super subscriber info (for inheritance) 3. Whether to check superclass 4. Whether to verify method naming conventions ``` -------------------------------- ### AsyncExecutor Execute with RunnableEx Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/async-executor.md Demonstrates executing a task with `AsyncExecutor` using the `RunnableEx` interface, which permits checked exceptions like `IOException` or `SQLException` to be thrown directly. ```java // With RunnableEx, checked exceptions are allowed AsyncExecutor.create().execute(() -> { // Can throw IOException, SQLException, etc. String data = fetchFromNetwork(); return data; }); ``` ```java // Equivalent with Runnable requires try-catch new Thread(() -> { try { String data = fetchFromNetwork(); } catch (IOException e) { // Handle or wrap } }).start(); ``` -------------------------------- ### EventSubscriber with Various ThreadModes Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/annotations-and-threadmode.md Demonstrates different EventBus ThreadModes for handling events. Use POSTING for immediate, non-blocking handling. Use MAIN for UI updates. Use MAIN_ORDERED for non-blocking main thread handling. Use BACKGROUND for I/O operations. Use ASYNC for heavy computation or parallel processing. ```java public class EventSubscriber { // Handle immediately in posting thread (fastest, no thread overhead) @Subscribe(threadMode = ThreadMode.POSTING) public void onQuickEvent(QuickEvent event) { updateLocalCache(event); } // Handle on main thread (for UI updates) @Subscribe(threadMode = ThreadMode.MAIN) public void onUIEvent(UIUpdateEvent event) { myTextView.setText(event.text); } // Handle on main thread, always queued (non-blocking even from main) @Subscribe(threadMode = ThreadMode.MAIN_ORDERED) public void onDialogEvent(ShowDialogEvent event) { new AlertDialog.Builder(context) .setMessage(event.message) .show(); } // Handle on background thread (for I/O operations) @Subscribe(threadMode = ThreadMode.BACKGROUND) public void onDataSync(DataSyncEvent event) { // Safe to do database operations, network calls syncDataWithServer(event.data); } // Handle in thread pool (for heavy computation or parallel processing) @Subscribe(threadMode = ThreadMode.ASYNC) public void onImageProcess(ProcessImageEvent event) { // Can run concurrently with other ASYNC handlers Bitmap processed = expensiveImageProcessing(event.image); EventBus.getDefault().post(new ImageProcessedEvent(processed)); } // High priority - processes first within POSTING mode @Subscribe(threadMode = ThreadMode.POSTING, priority = 10) public void onMessageValidate(MessageEvent event) { if (!validate(event)) { EventBus.getDefault().cancelEventDelivery(event); } } // Low priority - processes after validation @Subscribe(threadMode = ThreadMode.POSTING, priority = 0) public void onMessageProcess(MessageEvent event) { // Only reached if validation passed handleValidatedMessage(event); } // Sticky event - receives immediately on registration @Subscribe(sticky = true) public void onAppState(AppStateEvent event) { // Called immediately on registration if app state event was posted updateStateUI(event.state); } } ``` -------------------------------- ### EventBusBuilder Configuration Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/MANIFEST.txt Details on configuring a custom EventBus instance using the EventBusBuilder. ```APIDOC ## EventBusBuilder Configuration ### Description Allows for the creation and configuration of custom EventBus instances with various options, including thread pool sizes, subscriber index implementations, and logging. ### Configuration Methods - **`logNoSubscriberMessages(boolean logNoSubscriberMessages)`**: Enables or disables logging for events with no subscribers. - **`logSubscriberExceptions(boolean logSubscriberExceptions)`**: Enables or disables logging for subscriber exceptions. - **`sendSubscriberExceptionEvent(boolean sendSubscriberExceptionEvent)`**: Enables or disables sending `SubscriberExceptionEvent` on subscriber errors. - **`sendNoSubscriberEvent(boolean sendNoSubscriberEvent)`**: Enables or disables sending `NoSubscriberEvent` for events with no subscribers. - **`subscriberInfoIndexes(List subscriberInfoIndexes)`**: Sets custom `SubscriberInfoIndex` implementations for subscriber lookup. - **`asyncExecutor(AsyncExecutor asyncExecutor)`**: Provides a custom `AsyncExecutor` for background thread execution. - **`mainThreadSupport(MainThreadSupport mainThreadSupport)`**: Sets a custom `MainThreadSupport` implementation for main thread interactions. - **`poster(Poster poster)`**: Sets a custom `Poster` implementation for event delivery. - **`throwSubscriberException(boolean throwSubscriberException)`**: If true, subscriber exceptions will be re-thrown. - **`ignoreGeneratedIndex(boolean ignoreGeneratedIndex)`**: If true, generated subscriber indexes will be ignored. - **`eventInheritance(boolean eventInheritance)`**: If true, events will be delivered to subscribers listening for superclasses or interfaces. - **`installDefaultEventBus(boolean installDefaultEventBus)`**: If true, the configured EventBus will be installed as the default singleton instance. ### Usage Example ```java EventBus eventBus = EventBus.builder() .logSubscriberExceptions(true) .throwSubscriberException(false) .build(); ``` ``` -------------------------------- ### Handling EventBusException during Registration Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/events-and-errors.md Demonstrates how to catch and log an EventBusException that may occur during subscriber registration. ```java try { EventBus.getDefault().register(this); } catch (EventBusException e) { Log.e("EventBus", "Failed to register subscriber", e); // Fall back to alternative event handling } ``` -------------------------------- ### Build a New EventBus Instance Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/eventbus-builder.md Create a new EventBus instance with specific configurations. This method allows for isolated EventBus instances without affecting the default singleton. ```java EventBus customBus = EventBus.builder() .logSubscriberExceptions(false) .eventInheritance(false) .build(); ``` -------------------------------- ### Application Module Gradle Dependencies Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/annotation-processor.md This Gradle snippet configures the dependencies for an application module, including the EventBus library and its annotation processor. Ensure these are added for the processor to generate index files. ```gradle dependencies { implementation("org.greenrobot:eventbus:3.3.1") annotationProcessor("org.greenrobot:eventbus-annotation-processor:3.3.1") } ``` -------------------------------- ### Application Class EventBus Initialization Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/annotation-processor.md This Java snippet shows how to initialize EventBus in your Application class, registering all generated indexes from different modules. It also configures strict method verification for debug builds. ```java public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); // Register all generated indexes EventBus.builder() .addIndex(new AppIndex()) .addIndex(new FeatureIndex()) .strictMethodVerification(BuildConfig.DEBUG) .installDefaultEventBus(); } } ``` -------------------------------- ### Create EventBus Builder Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/eventbus.md Initializes a builder for configuring and constructing custom EventBus instances with specific options like logging and event inheritance. ```java public static EventBusBuilder builder() ``` ```java EventBus custom = EventBus.builder() .logSubscriberExceptions(false) .eventInheritance(false) .build(); ``` -------------------------------- ### Core EventBus Class API Reference Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/README.md Documentation of the main EventBus class, including static and instance methods for registering, unregistering, posting events, and managing sticky events. ```APIDOC ## EventBus Class API ### Description Provides core functionality for the EventBus library, including event posting, subscription management, and sticky event handling. ### Static Methods #### `getDefault()` - **Description**: Accesses the singleton instance of EventBus. - **Signature**: `public static EventBus getDefault()` #### `builder()` - **Description**: Creates a new `EventBusBuilder` to configure a custom EventBus instance. - **Signature**: `public static EventBusBuilder builder()` #### `clearCaches()` - **Description**: Clears internal caches used by EventBus. - **Signature**: `public static void clearCaches()` ### Instance Methods #### `register(Object subscriber)` - **Description**: Subscribes an object to receive events. - **Signature**: `public void register(Object subscriber)` #### `unregister(Object subscriber)` - **Description**: Unsubscribes an object from receiving events. - **Signature**: `public void unregister(Object subscriber)` #### `isRegistered(Object subscriber)` - **Description**: Checks if an object is currently registered as a subscriber. - **Signature**: `public boolean isRegistered(Object subscriber)` #### `post(Object event)` - **Description**: Posts an event to all registered subscribers. - **Signature**: `public void post(Object event)` #### `cancelEventDelivery(Object event)` - **Description**: Cancels the delivery of an event if it has not yet been delivered. - **Signature**: `public void cancelEventDelivery(Object event)` #### `postSticky(Object event)` - **Description**: Posts a sticky event, which remains in the bus until explicitly removed. - **Signature**: `public void postSticky(Object event)` #### `getStickyEvent(Class eventType)` - **Description**: Retrieves the last sticky event of the specified type. - **Signature**: `public T getStickyEvent(Class eventType)` #### `removeStickyEvent(Object event)` - **Description**: Removes a sticky event. - **Signature**: `public void removeStickyEvent(Object event)` #### `removeStickyEvent(Class eventType)` - **Description**: Removes the last sticky event of the specified type. - **Signature**: `public T removeStickyEvent(Class eventType)` #### `removeAllStickyEvents()` - **Description**: Removes all sticky events from the bus. - **Signature**: `public void removeAllStickyEvents()` #### `hasSubscriberForEvent(Class eventType)` - **Description**: Checks if there are any subscribers for a given event type. - **Signature**: `public boolean hasSubscriberForEvent(Class eventType)` #### `getLogger()` - **Description**: Retrieves the logger instance used by EventBus. - **Signature**: `public Logger getLogger()` ``` -------------------------------- ### Post an Event Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/quick-reference.md Post a new event instance to the EventBus. Any registered subscribers will receive it. ```java EventBus.getDefault().post(new MessageEvent("Hello!")); ``` -------------------------------- ### EventBus Registration Without Annotation Processor Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/annotation-processor.md This snippet shows the standard EventBus registration using reflection. It is slower, taking 5-50ms, due to the overhead of finding @Subscribe methods at runtime. ```java EventBus.getDefault().register(subscriber); // Takes ~5-50ms depending on method count // Uses reflection to find @Subscribe methods ``` -------------------------------- ### Subscribe with Priority Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/README.md Define the execution order for subscribers handling the same event. Higher priority values are executed first. ```java @Subscribe(priority = 10) public void onEventWithPriority(MyEvent event) { ... } ``` -------------------------------- ### post(Object event) Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/eventbus.md Posts an event to the event bus for immediate delivery to all registered subscribers. Events posted during an ongoing delivery are queued. ```APIDOC ## post(Object event) ### Description Posts an event to the event bus. The event is immediately delivered to all registered subscribers that have handler methods for the event type. If an event is posted from within a subscriber's event handler, it is queued and delivered after the current delivery completes. ### Method POST ### Endpoint EventBus.getDefault().post(event) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **event** (Object) - Required - The event to post. Can be any non-null object ### Request Example ```java EventBus.getDefault().post(new MessageEvent("Hello")); ``` ### Response #### Success Response (200) void #### Response Example None ``` -------------------------------- ### AsyncExecutor Builder for Customization Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/async-executor.md Illustrates using the `AsyncExecutor.builder()` to create a customized executor. This allows specifying a custom `EventBus`, a different thread pool, and a custom failure event type. ```java AsyncExecutor executor = AsyncExecutor.builder() .eventBus(myBus) .threadPool(Executors.newFixedThreadPool(4)) .failureEventType(MyCustomFailureEvent.class) .build(); ``` -------------------------------- ### Basic Async Task Execution Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/async-executor.md Execute a task asynchronously and post a success event. Handles potential failures with a default ThrowableFailureEvent. ```java public class DataLoader { public void loadUsers() { AsyncExecutor.create().execute(() -> { List users = fetchUsersFromDatabase(); EventBus.getDefault().post(new UsersLoadedEvent(users)); }); } @Subscribe public void onUsersLoaded(UsersLoadedEvent event) { updateUI(event.users); } @Subscribe public void onFailure(ThrowableFailureEvent event) { Log.e("DataLoader", "Failed to load users", event.getThrowable()); } } ``` -------------------------------- ### Register with Custom EventBus Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/quick-reference.md Create and use a custom EventBus instance with specific configurations. This allows for more control over EventBus behavior, such as disabling subscriber exception logging or event inheritance. ```java EventBus customBus = EventBus.builder() .logSubscriberExceptions(false) .eventInheritance(false) .build(); customBus.register(this); ``` -------------------------------- ### enqueue() Method Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/types-and-interfaces.md Queues an event for delivery to a specific subscription on the correct thread. This is an internal method for event dispatching. ```java void enqueue(Subscription subscription, Object event) ``` -------------------------------- ### Add Annotation Processor Dependency (Gradle) Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/annotation-processor.md Include the EventBus library and the annotation processor in your Gradle build file. This enables compile-time index generation. ```gradle dependencies { // EventBus library implementation("org.greenrobot:eventbus:3.3.1") // Annotation processor annotationProcessor("org.greenrobot:eventbus-annotation-processor:3.3.1") } ``` -------------------------------- ### AbstractSubscriberInfo Base Class Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/annotation-processor.md Provides default implementations for the SubscriberInfo interface. Generated classes extend this. ```java public abstract class AbstractSubscriberInfo implements SubscriberInfo ``` -------------------------------- ### Interfaces and Utility Classes Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/MANIFEST.txt Reference for various interfaces and utility classes used by EventBus for extensibility and custom implementations. ```APIDOC ## Interfaces and Utility Classes ### Description This section details the interfaces that allow for customization of EventBus behavior and utility classes used internally or for advanced scenarios. ### Core Interfaces - **`Logger`**: Interface for custom logging. Implementations can direct logs to different destinations. - **`MainThreadSupport`**: Interface to determine and interact with the main thread, crucial for Android UI updates. - **`Poster`**: Interface responsible for delivering events to subscribers based on their `ThreadMode`. - **`SubscriberInfo`**: Represents metadata about a subscriber, including its methods and their configurations. - **`SubscriberInfoIndex`**: An index that maps event types to `SubscriberInfo` objects, used for efficient subscriber lookup. - **`HasExecutionScope`**: Interface used to associate execution scope information, potentially for context propagation. - **`RunnableEx`**: An extended `Runnable` interface used by `AsyncExecutor`, allowing for exceptions within the `run` method. ### Metadata and Events - **`SubscriberMethod`**: A class holding information about a specific subscriber method, including its name, parameters, and `ThreadMode`. - **`NoSubscriberEvent`**: Event posted when an event has no subscribers. - **`SubscriberExceptionEvent`**: Event posted when a subscriber throws an exception. - **`ThrowableFailureEvent`**: A wrapper for `Throwable` failures. ### Custom Implementation Examples - **Custom Logger**: Implement the `Logger` interface to integrate with a specific logging framework. - **Custom Poster**: Create a custom `Poster` to modify event delivery behavior. - **Custom SubscriberInfoIndex**: Implement `SubscriberInfoIndex` for advanced subscriber lookup strategies, especially in multi-module projects or when using custom annotation processors. ``` -------------------------------- ### Enable Strict Method Verification Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/eventbus-builder.md Enables strict verification of subscriber methods, rejecting any methods that don't conform to exact specifications. Default is false. ```java public EventBusBuilder strictMethodVerification(boolean strictMethodVerification) ``` ```java EventBus bus = EventBus.builder() .strictMethodVerification(true) .build(); ``` -------------------------------- ### Sticky Event Subscription Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/annotations-and-threadmode.md Subscribing to sticky events allows immediate delivery of the most recent sticky event upon registration. Useful for state information. ```java // Post sticky event (retained for future subscribers) EventBus.getDefault().postSticky(new UserLoggedInEvent(user)); // Later, any new subscriber immediately receives it @Subscribe(sticky = true) public void onUserLoggedIn(UserLoggedInEvent event) { // Called immediately upon registration if a sticky event exists updateUIWithUser(event.user); } ``` -------------------------------- ### Define an Event Class Source: https://github.com/greenrobot/eventbus/blob/master/_autodocs/quick-reference.md Create a simple Java class to represent the event data that will be posted. ```java public class MessageEvent { public String message; public MessageEvent(String message) { this.message = message; } } ```