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

Related tags

EventBus 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
Powerful event-bus optimized for high throughput in multi-threaded applications. Features: Sync and Async event publication, weak/strong references, event filtering, annotation driven

MBassador MBassador is a light-weight, high-performance event bus implementing the publish subscribe pattern. It is designed for ease of use and aims

Benjamin Diedrichsen 931 Dec 23, 2022
Bus Scheduler - The source code for the Bus Scheduler app codelab

Bus Scheduler App This folder contains the source code for the Bus Scheduler app

Dania Puertas 0 Jan 7, 2022
An enhanced Guava-based event bus with emphasis on Android support.

Otto - An event bus by Square An enhanced Guava-based event bus with emphasis on Android support. Otto is an event bus designed to decouple different

Square 5.2k Jan 9, 2023
Event pattern & event properties framework

Renetik Android - Event & Property https://github.com/renetik/renetik-android-event Documentation Framework to enjoy, improve and speed up your applic

Renetik 2 Nov 2, 2022
The source code for the Bus Scheduler app codelab

Bus Scheduler App This folder contains the source code for the Bus Scheduler app codelab. Introduction The Bus Scheduler app displays a list of bus st

null 0 Nov 8, 2021
EventBus for Android,消息总线,基于SharedFlow,具有生命周期感知能力,支持Sticky,支持线程切换,支持延迟发送。

背景 跨页面通信是一个比较常见的场景,通常我们会选择使用EventBus,但EventBus无法感知声明周期,收到消息就会回调,所以有了LiveData之后很快就有了LiveEventBus。不过它也有缺点,比如不能切换线程。

BiuBiuQiu0 167 Jan 3, 2023
A lightweight eventbus library for android, simplifies communication between Activities, Fragments, Threads, Services, etc.

AndroidEventBus This is an EventBus library for Android. It simplifies the communication between Activities, Fragments, Threads, Services, etc. and lo

Mr.Simple 1.6k Nov 30, 2022
Powerful event-bus optimized for high throughput in multi-threaded applications. Features: Sync and Async event publication, weak/strong references, event filtering, annotation driven

MBassador MBassador is a light-weight, high-performance event bus implementing the publish subscribe pattern. It is designed for ease of use and aims

Benjamin Diedrichsen 931 Dec 23, 2022
PubSub - 使用 Kotlin Coroutines 实现的 Local Pub/Sub、Event Bus、Message Bus

PubSub 使用 Kotlin Coroutines 实现的 Local Pub/Sub、Event Bus、Message Bus 下载 将它添加到项目的

Tony Shen 4 May 30, 2022
A set of helper classes for using dagger 1 with Android components such as Applications, Activities, Fragments, BroadcastReceivers, and Services.

##fb-android-dagger A set of helper classes for using dagger with Android components such as Applications, Activities, Fragments, BroadcastReceivers,

Andy Dennie 283 Nov 11, 2022
Pass parameters safely and quickly between activities or fragments.

Bracer Pass parameters safely and quickly between activities or fragments. Read this in other languages: 中文, English, Change Log Prepare Add the JitPa

Season 57 Jan 3, 2023
Quality-Tools-for-Android 7.5 0.0 L5 Java This is an Android sample app + tests that will be used to work on various project to increase the quality of the Android platform.

Quality Tools for Android This is an Android sample app + tests that will be used to work on various project to increase the quality of the Android pl

Stéphane Nicolas 1.3k Dec 27, 2022
Bus Scheduler - The source code for the Bus Scheduler app codelab

Bus Scheduler App This folder contains the source code for the Bus Scheduler app

Dania Puertas 0 Jan 7, 2022
This prototype app provides a list of events to be held under an organization (school, college, club, etc.) and the users can manually set event reminders at their scheduled time so that they do not miss an event.

E-CELL NITS Sample App This prototype app provides a list of events to be held under E-Cell NIT Silchar (for example, Srijan 2.0) and the users can ma

Ritam Nath 1 Nov 7, 2021
A library for fast and safe delivery of parameters for Activities and Fragments.

MorbidMask - 吸血面具 Read this in other languages: 中文, English, Change Log A library for fast and safe delivery of parameters for Activities and Fragment

Season 67 Mar 29, 2022
An library to help android developers working easly with activities and fragments (Kotlin version)

AFM An library to help android developer working easly with activities and fragments (Kotlin) Motivation Accelerate the process and abstract the logic

Massive Disaster 12 Oct 3, 2022
An library to help android developers working easly with activities and fragments (Kotlin version)

AFM An library to help android developer working easly with activities and fragments (Kotlin) Motivation Accelerate the process and abstract the logic

Massive Disaster 12 Oct 3, 2022
LiteGo is a Java-based asynchronous concurrency library. It has a smart executor, which can be freely set the maximum number of concurrent at same time , and the number of threads in waiting queue. It can also set waiting policies and overload strategies.

LiteGo:「迷你」的Android异步并发类库 LiteGo是一款基于Java语言的「异步并发类库」,它的核心是一枚「迷你」并发器,它可以自由地设置同一时段的最大「并发」数量,等待「排队」线程数量,还可以设置「排队策略」和「超载策略」。 LiteGo可以直接投入Runnable、Callable

马天宇 189 Nov 10, 2022
A lightweight alternative to Android's ViewModels. The easiest way to retain instances in Activities, Fragments or Composables.

A lightweight alternative to Android's ViewModels. The easiest way to retain instances in Activities, Fragments or Composables.

Marcello Galhardo 264 Dec 27, 2022