EventBus

repository·master·Indexed 12 days ago

https://github.com/greenrobot/eventbus

A fast, lightweight publish/subscribe event bus for Android and Java that simplifies communication between decoupled components. It supports subscriber inheritance, sticky events, and flexible thread delivery (main, background, or posting thread). Available as a platform-agnostic Java library (org.greenrobot:eventbus-java) and an Android-optimized AAR (org.greenrobot:eventbus).

Tokens
1.8K
Snippets
5
Records
9
Agent score
98%

What's inside EventBus

  1. Compare EventBus with Square's Otto

    master

    If you are migrating from or choosing between greenrobot's EventBus and Square's Otto, note the following key functional differences:

    • Subscriber Inheritance: EventBus supports subscriber inheritance, whereas Otto does not.
    • Sticky Events: EventBus supports caching the most recent events (sticky events), while Otto does not.
    • Thread Delivery: EventBus allows event delivery in the main thread, background thread, or the posting thread, and supports asynchronous event delivery. Otto only supports delivery in the posting thread.
    • Event Handling: Both use annotations, but EventBus (since 3.0) can use precompiled annotations for optimal performance.
    • Event Inheritance: Both libraries support event inheritance.

    Performance Note: Benchmark results indicate that EventBus is significantly faster in most scenarios, including posting events, registering subscribers, and cold start registration.

  2. Understand the relationship between EventBus Android and EventBus Java

    master

    EventBus is split into two main components:

    1. org.greenrobot:eventbus (Android AAR): The primary dependency for Android developers. It includes the core logic and provides Android-specific optimizations.
    2. org.greenrobot:eventbus-java (Java JAR): The core, platform-agnostic library.

    The Android AAR automatically detects AndroidComponentsImpl on the classpath via reflection to provide an AndroidComponents implementation, enabling Android-specific features within the core Java logic.

  3. Configure R8 or ProGuard for EventBus

    master
    If your project uses R8 or ProGuard for code shrinking and obfuscation, EventBus includes embedded rules to ensure proper functionality. These rules are located in the library's consumer rules file.
  4. Add EventBus to your Android project

    master

    To use EventBus in an Android project, add the org.greenrobot:eventbus dependency. Although the module is named 'EventBus for Android', it is published under the artifact ID eventbus. This AAR dependency automatically includes the necessary Java-only core (org.greenrobot:eventbus-java) and provides an AndroidComponents implementation via reflection if AndroidComponentsImpl is detected on the classpath.

    dependencies {
        implementation 'org.greenrobot:eventbus:x.x.x' // Replace x.x.x with the latest version
    }
  5. Add EventBus to your project

    master

    EventBus is available on Maven Central. Choose the dependency based on your project type:

    • Android projects: Use org.greenrobot:eventbus.
    • Java projects: Use org.greenrobot:eventbus-java.
    // Android
    implementation("org.greenrobot:eventbus:3.3.1")
    
    // Java
    implementation("org.greenrobot:eventbus-java:3.3.1")
  6. Implement EventBus in 3 steps

    master

    To use EventBus, follow these three steps:

    1. Define events: Create a class to represent your event. It can be a simple POJO.
    2. Prepare subscribers:
      • Annotate a method with @Subscribe to handle specific events. You can optionally specify a threadMode (e.g., ThreadMode.MAIN).
      • Register the subscriber using EventBus.getDefault().register(this) and unregister it using EventBus.getDefault().unregister(this). In Android, it is recommended to register/unregister in lifecycle methods like onStart() and onStop().
    3. Post events: Use EventBus.getDefault().post(event) to broadcast an event to all registered subscribers.
    // 1. Define events
    public static class MessageEvent { /* Additional fields if needed */ }
    
    // 2. Prepare subscribers
    @Subscribe(threadMode = ThreadMode.MAIN)  
    public void onMessageEvent(MessageEvent event) {
        // Do something
    }
    
    // Register/Unregister (Android example)
    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }
    
    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }
    
    // 3. Post events
    EventBus.getDefault().post(new MessageEvent());
  7. Implement a custom Logger for EventBus

    master

    To monitor EventBus activity using your own logging framework, implement the org.greenrobot.eventbus.Logger interface. This interface provides two methods for logging messages with a java.util.logging.Level:

    1. log(Level level, String msg): Logs a simple message.
    2. log(Level level, String msg, Throwable th): Logs a message along with a Throwable stack trace.

    Once implemented, you can use your custom logger within your application's EventBus configuration.

    import org.greenrobot.eventbus.Logger;
    import java.util.logging.Level;
    
    public class MyCustomLogger implements Logger {
        @Override
        public void log(Level level, String msg) {
            // Your custom logging logic here
        }
    
        @Override
        public void log(Level level, String msg, Throwable th) {
            // Your custom logging logic here
        }
    }
  8. Use built-in Logger implementations

    master

    EventBus provides two convenient default implementations of the Logger interface:

    • JavaLogger: Wraps a standard java.util.logging.Logger. It requires a tag string in its constructor to identify the logger source.
    • SystemOutLogger: Redirects all log output to System.out, prefixing messages with the log level.

    Additionally, the Default.get() method returns a logger instance appropriate for the environment: it returns an Android-specific logger if AndroidComponents.areAvailable() is true, otherwise it returns a SystemOutLogger.

    // Using JavaLogger
    Logger myLogger = new Logger.JavaLogger("MyEventBusTag");
    
    // Using SystemOutLogger
    Logger myLogger = new Logger.SystemOutLogger();
    
    // Getting the environment-aware default logger
    Logger defaultLogger = Logger.Default.get();