Event bus for Android and Java that simplifies communication between Activities, Fragments, Threads, Services, etc. Less code, better quality.

Related tags

Messaging EventBus
Overview

EventBus

EventBus is a publish/subscribe event bus for Android and Java.

Build Status Follow greenrobot on Twitter

EventBus...

  • simplifies the communication between components
    • decouples event senders and receivers
    • performs well with Activities, Fragments, and background threads
    • avoids complex and error-prone dependencies and life cycle issues
  • makes your code simpler
  • is fast
  • is tiny (~60k jar)
  • is proven in practice by apps with 1,000,000,000+ installs
  • has advanced features like delivery threads, subscriber priorities, etc.

EventBus in 3 steps

  1. Define events:

    public static class MessageEvent { /* Additional fields if needed */ }
  2. Prepare subscribers: Declare and annotate your subscribing method, optionally specify a thread mode:

    @Subscribe(threadMode = ThreadMode.MAIN)  
    public void onMessageEvent(MessageEvent event) {/* Do something */};

    Register and unregister your subscriber. For example on Android, activities and fragments should usually register according to their life cycle:

     @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());

Read the full getting started guide.

There are also some examples.

Note: we highly recommend the EventBus annotation processor with its subscriber index. This will avoid some reflection related problems seen in the wild.

Add EventBus to your project

Available on Maven Central.

Via Gradle:

implementation 'org.greenrobot:eventbus:3.2.0'

Via Maven:

<dependency>
    <groupId>org.greenrobot</groupId>
    <artifactId>eventbus</artifactId>
    <version>3.2.0</version>
</dependency>

R8, ProGuard

If your project uses R8 or ProGuard add the following rules:

-keepattributes *Annotation*
-keepclassmembers class * {
    @org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }
 
# And if you use AsyncExecutor:
-keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent {
    <init>(java.lang.Throwable);
}

Homepage, Documentation, Links

For more details please check the EventBus website. Here are some direct links you may find useful:

Features

Documentation

Changelog

FAQ

How does EventBus compare to other solutions, like Otto from Square? Check this comparison.

License

Copyright (C) 2012-2020 Markus Junginger, greenrobot (https://greenrobot.org)

EventBus binaries and source code can be used according to the Apache License, Version 2.0.

Other projects by greenrobot

ObjectBox (GitHub) is a new superfast object-oriented database.

Essentials is a set of utility classes and hash functions for Android & Java projects.

greenDAO is an ORM optimized for Android: it maps database tables to Java objects and uses code generation for optimal speed.

Comments
  • NoClassDefFoundError android/os/PersistableBundle

    NoClassDefFoundError android/os/PersistableBundle

    When I install my app on Android 4.4 or less I receive this error:

    E/AndroidRuntime﹕ FATAL EXCEPTION: main java.lang.NoClassDefFoundError: android/os/PersistableBundle at java.lang.Class.getDeclaredMethods(Native Method) at java.lang.Class.getDeclaredMethods(Class.java:703) at de.greenrobot.event.SubscriberMethodFinder.findSubscriberMethods(SubscriberMethodFinder.java:75) at de.greenrobot.event.EventBus.register(EventBus.java:163) at de.greenrobot.event.EventBus.register(EventBus.java:133) at com.myapp.Domain.Login.Activities.LoginActivity.onCreate(LoginActivity.java:101)

    On LoginActivity.java:101 I just have

    EventBus.getDefault().register(this);

    opened by bkawakami 27
  • Support for plain old Java

    Support for plain old Java

    Rebased off annotations branch. Replacement for PR #174

    NB I can't get the annotations branch to build using IntelliJ. Not sure if the Gradle config in the branch has changed or my INtelliJ Gradle config has somehow lost its flavour (this is the only project I touch that uses Gradle).

    opened by william-ferguson-au 26
  • Annotation Support

    Annotation Support

    Hey, this looks like a great library, and I have been exploring using it. I know you guys have quite done quite a bit of research regarding Anotations vs Method Naming, but overall I really feel like Annotations are a much cleaner and more flexible solution.

    I added annotations to my local branch. You can create a new EventBus that uses annotations like this new EventBus(DeclarationType.ANNOTATIONS). Then you can subscribe to receive events on any method like this:

    @Subscribe public void onMyEvent(CustomEvent e)

    This uses the caller chooses thread method. We can also change this by adding an argument.

    @Subscribe(threadMode = ThreadMode.Background) public void onMyEvent(CustomEvent e)

    This uses the background thread and is definitely a more explicit syntax.

    Here is a link to my repo where I implemented the changes. https://github.com/rjbrock/EventBus

    I would still need to add unit tests before submitting a pull request so I just wanted to see what your thoughts were first.

    Rick

    confirmed feature 
    opened by rjbrock 23
  • AndroidX support

    AndroidX support

    Now that Android Studio 3.2.0 and androidx 1.0.0 libraries have been released, is there a plan to migrate to androidx? Google has said there won't be any more feature releases under the android.support packaging.

    opened by cckroets 22
  • Fatal Exception: java.lang.NoClassDefFoundError android/telephony/CellInfoGsm

    Fatal Exception: java.lang.NoClassDefFoundError android/telephony/CellInfoGsm

    Hi, On specific mobiles eventbus crashes with following error.

    Fatal Exception: java.lang.NoClassDefFoundError android/telephony/CellInfoGsm de.greenrobot.event.SubscriberMethodFinder.findSubscriberMethods Caused by java.lang.ClassNotFoundException

    dalvik.system.BaseDexClassLoader.findClass (BaseDexClassLoader.java:61)

    java.lang.Class.getDeclaredMethods (Class.java:703)

    de.greenrobot.event.SubscriberMethodFinder.findSubscriberMethods (SubscriberMethodFinder.java:75)

    de.greenrobot.event.EventBus.register (EventBus.java:163)

    de.greenrobot.event.EventBus.registerSticky (EventBus.java:151)

    Looks like findSubscriberMethods is trying to access methods which are marked as @TargetApi(17) while the phone is using api 16. Hence eventbus is not able to find those classes which are not available in api 16. Looks like a bug. Is there any workaround?

    opened by pankajchandiitm 22
  • Changed library to use annotations

    Changed library to use annotations

    The library now requires the use of annotations in order for a method to be subscribed to an event.

    @Subscribe public void mySubscribingMethod(MyEvent event)

    opened by rjbrock 18
  • How to stop onEventMainThread

    How to stop onEventMainThread

    First of all, thank for project. My question: How to stop onEventMainThread after destroy fragment ?? Some events i don't want to excute after destroy because it maybe no found views and lead to crash app Thanks

    support / not an issue 
    opened by tuanth89 17
  • R8 @subscribe annotation

    R8 @subscribe annotation

    Im getting the "classic" error using this library with proguard, but now with r8 the "classic" solution https://stackoverflow.com/a/39387526/3994630 is not working. Any idea?

    more info required 
    opened by pcg92 13
  • Let exceptions crash the app

    Let exceptions crash the app

    Hi, if I have an Exception that would normally crash the app within the onEvent callback method the app doesn't crash and the exception is logged by EventBus. Is there a way to change that behaviour to the default one (exception -> crash) ?

    confirmed feature 
    opened by fmweigl 13
  • org.greenrobot.eventbus.EventBusException: Subscriber class XXX and its super classes have no public methods with the @Subscribe annotation

    org.greenrobot.eventbus.EventBusException: Subscriber class XXX and its super classes have no public methods with the @Subscribe annotation

    I'm trying to use EventBus in my project, but I'm stuck with a strange exception thrown by EventBus when trying to get my App running.

    The case is I'm using EventBus in a custom view where I register EventBus in the onAttachToWindow() method and unregister it in the onDetachFromWindow() method. And then I created a method like this:

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventReceived(MessageEvent event) {
        //TODO
    }
    

    The problem is when I run the App, an exception is thrown which is really weird: org.greenrobot.eventbus.EventBusException: Subscriber class XXX and its super classes have no public methods with the @Subscribe annotation

    Can anyone help with this? Any suggestions is welcomed.

    opened by PanWangJ 12
  • Gradle apt error for eventBusIndex...

    Gradle apt error for eventBusIndex...

    I've wrestled with this for the past couple of hours or so, but cannot get gradle to build my index. I get the following error: warning: The following options were not recognized by any processor: '[eventBusIndex]'

    Here are snippets of my build.gradle file. I also have apt working for dagger 2.0, so I know my apt configuration works:

    buildscript {
        repositories {
            mavenCentral()
            maven { url 'https://maven.fabric.io/public' }
        }
    
        dependencies {
            classpath 'io.fabric.tools:gradle:1.21.5'
            classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
            classpath 'me.tatarka:gradle-retrolambda:3.2.5'
        }
    }
    
    repositories {
        mavenCentral()
    }
    
    apply plugin: 'com.android.application'
    apply plugin: 'com.neenbedankt.android-apt'
    apply plugin: 'me.tatarka.retrolambda'
    
    dependencies {
        compile 'org.greenrobot:eventbus:3.0.0'
        apt 'org.greenrobot:eventbus-annotation-processor:3.0.1'
    }
    
    apt {
        arguments {
            eventBusIndex "com.example.EventBusAppIndex"
        }
    }
    

    Any pointers on what I may be missing?

    Thanks a lot for a fantastic library btw. I've used 2.x version extensively in past projects

    opened by onomated 12
  • Support a Kotlin coroutines ThreadMode for Subscribe methods

    Support a Kotlin coroutines ThreadMode for Subscribe methods

    It would be nice if there was support for using a coroutines dispatcher to dispatch long running subscribe methods in the background. This would be similar in functionality to ThreadMode.ASYNC. But instead of using a thread pool where each subscribe consumes a thread until it completes, the subscribe method would be able to suspend execution and yield the thread to other subscribers to start processing.

    How I'd imagine this would look in Kotlin code would be:

    class Obj {
      @Subscribe(threadMode = ThreadMode.COROUTINE) // could also be ThreadMode.SUSPENDABLE
      suspend fun longRunningSubscriber(event: Event) {
        // do something
        // suspend for some long running IO
        // do something else
      }
    }
    

    Taking a quick look at the EventBus logic there are a couple things that would need to be implemented/updated.

    1. The logic that finds subscribe methods would need to be able to recognize suspendable methods.
      • When Kotlin code is compiled to Java, suspend methods have a Continuation parameter added to the Java method signature.
    2. a CoroutinesPoster (similar in concept to AsyncPoster) would need to be created that would dispatch the corresponding suspendable method using a coroutines Dispatcher.

    If you don't want to include kotlin/coroutines logic in the main EventBus artifact, I would be fine if this was some sort of optional support that is only available if you import an additional module into the class path & add some configuration to the EventBus object that activates the additional module.

    Currently there are a couple possible workarounds to get a coroutine context within a subscriber.

    • use runBlocking {} on an ASYNC subscriber which will provide a coroutine context, but this will still block the ASYNC thread until runBlocking completes and doesn't efficiently use threads.
    • don't make the subscriber suspendable, but instead launch a background coroutine from the subscriber method to do the long running processing.
    feature 
    opened by frett 1
  • Can you support the OpenHarmony JavaScript version?

    Can you support the OpenHarmony JavaScript version?

    I am developing an OpenHarmony application with JavaScript language which used your library, will your library support OpenHarmony platform by JavaScript language? if so, I want to contribute to the OpenHarmony build of this library. Expecte foe your reply!

    more info required 
    opened by DoraCoder 1
  • The service cannot receive eventbus events.

    The service cannot receive eventbus events.

    MyService.java

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMyEvent(MyEvent event){
        Log.e(TAG,"onEvent");
    }
    

    MyFragment.java

    EventBus.getDefault().post(new MyEvent());


    manifast.xml

    <application
        android:name="com.xxxx"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true"
        tools:ignore="GoogleAppIndexingWarning,UnusedAttribute">
      <service android:name=".MyService" />
    

    ======================================================= ps1: MyFragment send the event after MyService started. ps2: EventBus version : 3.1.1 android minSdkVersion 14 android targetSdkVersion 28

    more info required 
    opened by libq 1
  • Deadlock risk while register sticky event

    Deadlock risk while register sticky event

    When we register event listener by sticky, there is a risk of deadlock. Because when register a sticky event, it may invoke the event handler method, if the event handler method tries to acquire a lock to do something, at the same time another thread already acquires the lock and try to post an event, deadlock happend.

    If we can optimize the register code to avoid this risk, that will be great!!

    opened by tangnan526 0
  • SubscriberMethodFinder field optimization.

    SubscriberMethodFinder field optimization.

    I found that there is subscriberInfoIndexes field in SubscriberMethodFinder that can be set to final,And I observe that this field is only assigned in the constructor,So I set this field to final. I don't know if this modification is in line with your expectations.

    opened by Quyunshuo 2
Releases(V3.3.1)
  • V3.3.1(Dec 8, 2021)

    For Java projects, version 3.3.0 and higher require adding a new dependency. See the 3.3.0 release notes.

    • Fix ProGuard rule for ThrowableFailureEvent to only apply to itself, not subclasses. (ThrowableFailureEvent is the default failure event type used by AsyncExecutor.) #685
    Source code(tar.gz)
    Source code(zip)
  • V3.3.0(Dec 6, 2021)

    The eventbus artifact now ships as an Android library (AAR).

    For Android projects no changes are necessary.

    For Java-only projects, make sure to update your dependencies to point to the new eventbus-java library:

    // Replace:
    implementation("org.greenrobot:eventbus:3.2.0")
    // With:
    implementation("org.greenrobot:eventbus-java:3.3.0")
    

    Notable changes

    • Migrate to AndroidX. Thanks @andob! #552
    • Embed ProGuard/R8 rules #652
    Source code(tar.gz)
    Source code(zip)
  • V3.2.0(Feb 12, 2020)

  • V3.1.1(Aug 27, 2018)

  • V3.0.0(Feb 4, 2016)

    Annotations!

    Full announcement: http://greenrobot.org/release/eventbus-3-release-annotations/

    Gradle dependency:

    compile 'org.greenrobot:eventbus:3.0.0'
    
    Source code(tar.gz)
    Source code(zip)
  • V2.4.0(Nov 11, 2014)

  • V2.3.0(Nov 11, 2014)

    • New EventBusBuilder to configure EventBus instances (including the getDefault() instance, #124)
    • Added configuration to disable "No subscribers registered for event" logs (EventBusBuilder, #107, #117)
    • Added configuration to disable sending SubscriberExceptionEvent and NoSubscriberEvent (EventBusBuilder)
    • Added configuration to fail when subscribers throw exceptions (EventBusBuilder, #55)
    • Added configuration to use an existing thread pool (EventBusBuilder, #115)
    • Added configuration to disable event inheritance improving performance for apps with high event rates (EventBusBuilder)
    • Fixed performance regression sneaked into V2.2.x affecting (first time) registration of subscribers
    • Updated to Gradle 2.1, using wrapper
    • EventBusTest and EventBusPerformance use Gradle to build
    • Added hasSubscriberForEvent to check if currently subscribers exist registered to a given event type
    • Improved README.md and extracted an extended HOWTO.md and CHANGELOG.md from it
    • Ignore compiler generated methods (#76)
    • Various small code improvements (#120 among many others)

    Note: This is your last chance to use APIs that were deprecated in V2.2.0. It's recommended to switch to Version 2.4.0 (or above) at your earliest convenience.

    Source code(tar.gz)
    Source code(zip)
Owner
Markus Junginger
CTO and co-founder at objectbox.io, creator of EventBus and greenDAO.
Markus Junginger
Evgeniy Khyst 54 Dec 28, 2022
A distributed event bus that implements a RESTful API abstraction on top of Kafka-like queues

Nakadi Event Broker Nakadi is a distributed event bus broker that implements a RESTful API abstraction on top of Kafka-like queues, which can be used

Zalando SE 866 Dec 21, 2022
EventStoreDB is the database for Event Sourcing. This repository provides a sample of event sourced system that uses EventStoreDB as event store.

Event Sourcing with EventStoreDB Introduction Example Domain Event Sourcing and CQRS 101 State-Oriented Persistence Event Sourcing CQRS Advantages of

Evgeniy Khyst 53 Dec 15, 2022
Real Time communication library using Animated Gifs as a transport™

gifsockets "This library is the websockets of the '90s" - Somebody at Hacker News. This library shows how to achieve realtime text communication using

Alvaro Videla 1.8k Dec 17, 2022
Tiny and fast event dispatcher.

HookDispatcher - Tiny and fast event dispatcher. Installation Gradle repositories { maven { url 'https://jitpack.io' } } dependencies { imple

null 8 Dec 7, 2021
Plugin for keycloak that serves as an event listener, displaying user information in the log when there are registration and login events

Keycloak - Event listener Details Plugin for keycloak that serves as an event listener, displaying user information in the log when there are registra

José alisson 2 Jan 14, 2022
A modular and portable open source XMPP client library written in Java for Android and Java (SE) VMs

Smack About Smack is an open source, highly modular, easy to use, XMPP client library written in Java for Java SE compatible JVMs and Android. A pure

Ignite Realtime 2.3k Dec 28, 2022
Firehose is an extensible, no-code, and cloud-native service to load real-time streaming data from Kafka to data stores, data lakes, and analytical storage systems.

Firehose - Firehose is an extensible, no-code, and cloud-native service to load real-time streaming data from Kafka to data stores, data lakes, and analytical storage systems.

Open DataOps Foundation 279 Dec 22, 2022
Dagger is an easy-to-use, configuration over code, cloud-native framework built on top of Apache Flink for stateful processing of real-time streaming data.

Dagger Dagger or Data Aggregator is an easy-to-use, configuration over code, cloud-native framework built on top of Apache Flink for stateful processi

Open DataOps Foundation 238 Dec 22, 2022
Microservice-based online payment system for customers and merchants using RESTful APIs and message queues

Microservice-based online payment system for customers and merchants using RESTful APIs and message queues

Daniel Larsen 1 Mar 23, 2022
gMark: a domain- and query language-independent graph instance and query workload generator

gMark is a domain- and query language-independent graph instance and query workload generator.

Roan 3 Nov 19, 2022
KC4Streams - a simple Java library that provides utility classes and standard implementations for most of the Kafka Streams pluggable interfaces

KC4Streams (which stands for Kafka Commons for Streams) is a simple Java library that provides utility classes and standard implementations for most of the Kafka Streams pluggable interfaces.

StreamThoughts 2 Mar 2, 2022
Kafka example - a simple producer and consumer for kafka using spring boot + java

Kafka example - a simple producer and consumer for kafka using spring boot + java

arturcampos 1 Feb 18, 2022
Efficient reliable UDP unicast, UDP multicast, and IPC message transport

Aeron Efficient reliable UDP unicast, UDP multicast, and IPC message transport. Java and C++ clients are available in this repository, and a .NET clie

Real Logic 6.3k Jan 9, 2023
Apache Camel is an open source integration framework that empowers you to quickly and easily integrate various systems consuming or producing data.

Apache Camel Apache Camel is a powerful, open-source integration framework based on prevalent Enterprise Integration Patterns with powerful bean integ

The Apache Software Foundation 4.7k Dec 31, 2022
Fast and reliable message broker built on top of Kafka.

Hermes Hermes is an asynchronous message broker built on top of Kafka. We provide reliable, fault tolerant REST interface for message publishing and a

Allegro Tech 742 Jan 3, 2023
This repository contains a functional example of an order delivery service similar to UberEats, DoorDash, and Instacart.

Order Delivery Microservice Example In an event-driven microservices architecture, the concept of a domain event is central to the behavior of each se

Kenny Bastani 198 Dec 7, 2022
Dataflow template which read data from Kafka (Support SSL), transform, and outputs the resulting records to BigQuery

Kafka to BigQuery Dataflow Template The pipeline template read data from Kafka (Support SSL), transform the data and outputs the resulting records to

DoiT International 12 Jun 1, 2021
An example Twitch.tv bot that allows you to manage channel rewards (without requiring a message), and chat messages.

Twitch Bot Example shit code that can be used as a template for a twitch bot that takes advantage of channel rewards (that dont require text input) an

Evan 3 Nov 3, 2022