A lightweight eventbus library for android, simplifies communication between Activities, Fragments, Threads, Services, etc.

Overview

AndroidEventBus Logo AndroidEventBus

This is an EventBus library for Android. It simplifies the communication between Activities, Fragments, Threads, Services, etc. and lowers the coupling among them to a great extent, thus making simplifier codes, lower coupling possible and improving code quality.

  中文版 README.md.【该项目不再维护】    

new feature

  1. support sticky event;

AndroidEventBus is adopted in the following app

Basic Architecture

arch

AndroidEventBus is like the Observer Pattern. It will have the objects which need to subscribe events registered into the EventBus through Function “register” and store such subscription methods and subscription objects in Map. When a user posts an event somewhere, the EventBus will find corresponding subscription object in accordance with the parameter type and tag of the Event and then execute the method in subscription object. These subscription methods will be executed in the Thread Mode designated by the user. For example, mode=ThreadMode. ASNYC means the subscription method is executed in the sub-thread. Please refer to the following instructions for more details.

Code Example

You can use AndroidEventBus according to the following steps.

    1. Event-receiving Object
   
public class YourActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        // register the receiver object
        EventBus.getDefault().register(this);
    }
    
   @Override
    protected void onDestroy() {
        // Don’t forget to unregister !!
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
   
    1. Mark the receiving method of the Event-receiving Object with Subscriber annotation.
public class YourActivity extends Activity {
 
    // code ......
    
    // A receiving method with a default tag will execute on UI thread.
    @Subscriber
    private void updateUser(User user) {
        Log.e("", "### update user name = " + user.name);
    }

	// When there is a “my_tag”, only events designated with “my_tag” can 
	// trigger the function and execute on UI thread when a user posts an event.
    @Subscriber(tag = "my_tag")
    private void updateUserWithTag(User user) {
        Log.e("", "### update user with my_tag, name = " + user.name);
    }
    
	// When there is a “my_tag”, only events designated with “my_tag” can trigger the function.
	// The function will execute on the same thread as the one post function is executed on.   
    @Subscriber(tag = "my_tag", mode=ThreadMode.POST)
    private void updateUserWithMode(User user) {
        Log.e("", "### update user with my_tag, name = " + user.name);
    }

	// When there is a “my_tag”, only events designated with “my_tag” can trigger  
	// the function and execute on an independent thread when a user posts an event.
    @Subscriber(tag = "my_tag", mode = ThreadMode.ASYNC)
    private void updateUserAsync(User user) {
        Log.e("", "### update user async , name = " + user.name + ", thread name = " + Thread.currentThread().getName());
    }
}

User class is approximately as follows :

    public class User  {
        String name ;
        public User(String aName) {
            name = aName ;
        }
    }

The receiving function will use “tag” to mark receivable types of events, just like designating “action” in BroadcastReceiver, which can deliver messages precisely. Mode can designate which thread the object function will be executed on but defaultly it will be executed on UI thread for the purpose of convenient UI update for users. When the object method executes long-running operations, the “mode” can be set as ASYNC so as to be executed on sub-thread.

    1. To post an event in other components such as Activities, Fragments or Services.
    
    EventBus.getDefault().post(new User("android"));
    
    // post a event with tag, the tag is like broadcast's action
    EventBus.getDefault().post(new User("mr.simple"), "my_tag");
    
    // post sticky event
    EventBus.getDefault().postSticky(new User("sticky"));

After posting the event, the object registered with the event type will receive responsive event.

Usage

integrate with jar

It will be enough to add the jar file into the “quote” part of the Project, AndroidEventBus.AndroidEventBus.jar

Gradle

  • Add dependency in build.gradle of the Module .
dependencies {

    // add AndroidEventBus dependency
    compile 'org.simple:androideventbus:1.0.5.1'
}

Differing from the EventBus of greenrobot

  1. EventBus of greenrobot is a popular open source library but its user experience is not as friendly. For example, its subscription function is required to start with onEvent, and if a function’s execution thread needs to be designated, it is necessary to add the mode name of execution thread in the name of the function according to certain rules. This may be difficult to understand. Let’s say, if I want the receiving function of some event to be executed on the main thread, I am required to name it as onEventMainThread. What if two of my subscribers share the same parameter name and both are executed on the receiving function of the main thread? It seems impossible to deal with it in such case. And a set-in-stone function name can’t properly reflect the function of the Function, i.e., the self-documentation of the function. AndroidEventBus uses annotation to mark receiving function, by which the function name is not limited. For example, I can name the receiving function as updateUserInfo(Person info). It’s more flexible.
  2. Another difference lies in that AndroidEventBus adds an extra tag to mark the tag of receivable event of every receiving function, just like the action in Broadcast. For instance, one Broadcast corresponds to one or more actions, and you need to designate the action of a broadcast before you can publish one and the broadcast receiver can receive. EventBus of greenrobot marks whether a function can receive a certain event only by the parameter type of the function. In this way, the function can receive all the events of the same parameter type, resulting in a limited delivery principle. Let’s say, if there are two events: one is about adding user and the other is about deleting user. Their parameter types are both User. Then the EventBus of greenrobot would be lke:

private void onEventMainThread(User aUser) {
	// code 
}

If there are two receiving functions of the same parameter type and both are executed on the main thread, how to name them distinctively? Supposing that there are two functions meeting the requirements and the event is adding user, but because the EventBus judges receiving function only by parameter type of the event, both function will be executed. The strategy of AndroidEventBus is to add a “tag” for each event, and use parameter type and “tag” to jointly mark the uniqueness of the vent so as to ensure precise delivery.

These are the differences between AndroidEventBus and EventBus of greenrobot. But it is understandable for greenrobot’s approach considering performance. And what I try to express is that there are very limited quantity of events posted in an App and the performance difference is negligible while user experience is well sensible. What I need to point out is that I know little about the ins and outs of EventsBus of greenrobot and there could be errors among what I’ve mentioned. If that happens, you are more than welcome to correct me.

Comparison Of Characteristics

library Whether the subscription function can be executed on other thread features
greenrobot's EventBus yes It adopts name pattern which is efficient but inconvenient to use.
square's otto no It is convenient to use annotation but it’s not as efficient as EventBus
AndroidEventBus yes It is convenient to use annotation but it’s not as efficient as EventBus. The subscription supports tag (like the Action in Broadcast Receiver) which can make event delivery more accurate and applicable to more usage scenarios.

Proguard

-keep class org.simple.** { *; }
-keep interface org.simple.** { *; }
-keepclassmembers class * {
    @org.simple.eventbus.Subscriber 
   
    ;
}
-keepattributes *Annotation*

   

Thanks Note

I really appreciate E-pal “淡蓝色的星期三” for his proposing of bugs and feedback and I hope more and more friends will join our team of AndroidEventBus Development.

Release Note

V1.0.5 ( 2015.6.20 )

  1. fix bugs.

V1.0.4 ( 2015.5.23 )

  1. support Sticky Events and use WeakReference to hold the Subscriber.

V1.0.2 ( 2015.2.28 )

Solved the problem of failing to receive an event when the parameter of the subscription method is a basic type (int, Boolean, etc.)

V1.0.1 ( 2015.2.13 )

  1. Solved the problem that the subscription method can’t receive an event because the subscription method is delivered as sub-type when posting an event while it was originally of basic type.

v1.0 ( 2015.2.9 )

  1. Release an EventBus library; use @Subscriber annotation to mark subscription method
  2. The subscription method supports “tag” mark, which makes event delivery more precise.

License

Copyright (C) 2015 Mr.Simple 
   
    

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

   
Comments
  • 和您探讨EventBus的一些问题

    和您探讨EventBus的一些问题

    如果同是在主线程上接收,参数又一样的两个接受方法, 这样的情况, 其实在EventBus没有很好地支持,其实最好的做法我觉得是 onEvent***(id, Event)的形式就更精确了 不过robot的EventBus其实也可以处理这些东西, 就是一开始在设计是就把所有事件类,如AEvent, BEvent, CEvent全继承自一个基类,这个基类有一个id的参数。 这样能解决这个问题,就是麻烦些。

    opened by songzhw 17
  • 针对README中“与greenrobot的EventBus的不同”的话题提出几点自己的看法↓↓↓

    针对README中“与greenrobot的EventBus的不同”的话题提出几点自己的看法↓↓↓

    • 针对“与greenrobot的EventBus的不同”中所指出的第一个问题,EventBus 3.x之后已经通过引入注解解决了这个问题,解放了方法名,方法名可以根据开发者的业务自己定义,体现代码的自文档性。
    • 针对“与greenrobot的EventBus的不同”中所指出的第二个问题,个人认为二次封装,引入tag没有必要,tag(或者叫type)之类的区别事件post源头的字段完全可以放在User或者UserEvent的实体类中,post事件时传且仅传实体类,多个post传递到一个Subscriber之后通过取出类中的tag(或者type)来通过if或switch来区别post的源头。

    综上,本库之前相比于EventBus的优势随着EventBus的升级而式微,EventBus已经足够精简和友好了,没有必要再针对其进行二次封装,徒增学习成本和维护成本。

    opened by yangyiRunning 10
  • EventBus.getDefault().post(true,

    EventBus.getDefault().post(true, "procress"); can't receiver

    EventBus.getDefault().post(true, "procress");
    
    @Subcriber(tag = "procress")
    public void onEvent(boolean isShow){
    
    }
    

    使用boolean,會無法接收到,請問是否要改成

    @Subcriber(tag = "procress")
    public void onEvent(Boolean isShow){
    
    }
    
    opened by Jakevin 8
  • 最新版本,无法post空对象

    最新版本,无法post空对象

    EventBus.getDefault().post(null, LoginEvent.TAG_EVENT); 空指针异常~~ 看了下源码,里面有做类型转化。。

    07-28 18:28:49.449: E/AndroidRuntime(17063): java.lang.NullPointerException
    07-28 18:28:49.449: E/AndroidRuntime(17063):    at org.simple.eventbus.EventBus.post(EventBus.java:188)
    07-28 18:28:49.449: E/AndroidRuntime(17063):    at co.sihe.hongmi.fragment.settings.SettingFragment$4.onClick(SettingFragment.java:88)
    07-28 18:28:49.449: E/AndroidRuntime(17063):    at android.view.View.performClick(View.java:4633)
    07-28 18:28:49.449: E/AndroidRuntime(17063):    at android.view.View$PerformClick.run(View.java:19323)
    07-28 18:28:49.449: E/AndroidRuntime(17063):    at android.os.Handler.handleCallback(Handler.java:733)
    07-28 18:28:49.449: E/AndroidRuntime(17063):    at android.os.Handler.dispatchMessage(Handler.java:95)
    07-28 18:28:49.449: E/AndroidRuntime(17063):    at android.os.Looper.loop(Looper.java:157)
    07-28 18:28:49.449: E/AndroidRuntime(17063):    at android.app.ActivityThread.main(ActivityThread.java:5293)
    07-28 18:28:49.449: E/AndroidRuntime(17063):    at java.lang.reflect.Method.invokeNative(Native Method)
    07-28 18:28:49.449: E/AndroidRuntime(17063):    at java.lang.reflect.Method.invoke(Method.java:515)
    07-28 18:28:49.449: E/AndroidRuntime(17063):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
    07-28 18:28:49.449: E/AndroidRuntime(17063):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
    07-28 18:28:49.449: E/AndroidRuntime(17063):    at dalvik.system.NativeStart.main(Native Method)
    
    opened by hwangjr 5
  • 关于unregister是否调用的问题(1.0.4 )

    关于unregister是否调用的问题(1.0.4 )

    我在LoginActivity注册了User实体类的回调事件(当接收到User实体类时,则认为登录成功,在其他页面接收到的时候,则刷新当前页面),LoginActivity在接收到User之后,弹出Toast告知用户已经登录成功,并且finish掉自己.期望LoginActivity在onDestroy后,能即时的注销回调,不再接收User事件.然而 这时候有可能出现Subscriber还没有被回收的情况.出现再次触发了已经onDestroy的LoginActivity.. 不符合初期的期望,...这不禁让我有些疑惑.当Activity的onDestroy执行之后,Subscriber什么时机会被系统回收呢? 是否又会因此影响到之前的代码逻辑,以及unregister定位于过时方法是否合理?

    小子的代码不漂亮,如果有时间请多多指教~

    opened by lixi0912 5
  • post的event为基本数据类型时Subscriber接收不到

    post的event为基本数据类型时Subscriber接收不到

    只有将event封装到对象的post事件能接收到。

    e.g

            EventBus.getDefault().post(
                       Long.valueOf(SystemClock.elapsedRealtime()),   //works
    //                 SystemClock.elapsedRealtime(),                          //not work
                       Constants.EVENT_TIMER_UPDATE);
    
    opened by ydcool 5
  • 一對多的情況(One Activity post to 2 fragmnet)

    一對多的情況(One Activity post to 2 fragmnet)

    問題 Q

    //Activity has a Fragmnet
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);    
        EventBus.getDefault().post("Jay Music","ticket");
    }
    
    @Subcriber(tag = "ticket")
    public void onEvent(String event) {
        Log.e("","I got " + event +"ticket")
    }
    

    在Activity是沒有問題的,可以看到Log at Activity ,Log is showing

    //Fragment
    @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            EventBus.getDefault().register(this);    
    }
    
    @Subcriber(tag = "ticket")
    public void onEvent(String event) {
        Log.e("","I got " + event +"ticket")
    }
    

    但在Fragment上卻無法顯示Log Bug at Fragment , I can't get Log

    opened by Jakevin 2
  • 有時會重複接收

    有時會重複接收

    Hi~

    我測試到 Subcriber 的 function,有時會被執行兩次

       //這個只有發過一次
        EventBus.getDefault().post(list, EventBusTag.IMTag.CHAT_GET_QUERY_MSG);
    
    //這邊收到兩次
    @Subcriber(tag = EventBusTag.IMTag.CHAT_GET_QUERY_MSG)
        public void onQueryMsgGet(List<Message> list){
            if(adapter!=null){
                adapter.clear();
                adapter.addAll(list);
                JKLog.i("","onQueryMsgGet");
            }
        }
    
    opened by Jakevin 1
  • 和您探讨EventBus的一些问题

    和您探讨EventBus的一些问题

    如果同是在主线程上接收,参数又一样的两个接受方法, 这样的情况, 其实在EventBus没有很好地支持,其实最好的做法我觉得是 onEvent***(id, Event)的形式就更精确了 不过robot的EventBus其实也可以处理这些东西, 就是一开始在设计是就把所有事件类,如AEvent, BEvent, CEvent全继承自一个基类,这个基类有一个id的参数。 这样能解决这个问题,就是麻烦些。

    opened by songzhw 0
  • AndroidEventBus的优化建议

    AndroidEventBus的优化建议

    (1)EventBus里面的handleStickyEvent方法最后执行的判断条件冗余,因为通过foundEventType找到的subscription其eventType一定和foundType相等。所以判断条件只需要isTarget(subItem, subscriber)即可

    (2)经过第一步之后,Subscription里面的EventType就没有被用到,可以去掉了。因为EventType在mSubscribeMap是Key的角色,Subscription本质是value的角色,value里面含有key很奇怪

    (3)TargetMethod这个类,感觉有点冗余,这个类只在SubscribeMethodHunter里面使用,它从findSubcribeMethods(...)方法里面接收Method , EventType type, ThreadMode 参数,然后传递给subscibe(EventType event, TargetMethod method, Object subscriber)使用,建议把subscribe(...)方法改成 private void subscibe(EventType event, Object subscriber, Method method, ThreadMode threadMode) ,这样TargetMethod这个类也可以优化掉。

    opened by xiaweicheng 1
Owner
Mr.Simple
┈╭━━━━━━━━━━━╮┈ ┈┃╭━━━╮┊╭━━━╮┃┈ ╭┫┃┈:two_hearts:┈┃┃┈:two_hearts:┈┃┣╮ ┃┃╰━━━╯┊╰━━━╯┃┃ ╰┫╭━╮╰━━━╯╭━╮┣╯ ┈┃┃┣┳┳┳┳┳┳┳┫┃┃┈ ┈┃┃╰┻┻┻┻┻┻┻╯┃┃┈ ┈╰━━━━━━━━━━━╯┈
Mr.Simple
EventBus for Android,消息总线,基于SharedFlow,具有生命周期感知能力,支持Sticky,支持线程切换,支持延迟发送。

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

BiuBiuQiu0 167 Jan 3, 2023
Eventbus implemented by Flow

FlowBus FlowVersion EventBus Usage Add it in your root build.gradle at the end of repositories

wenchieh 3 Jun 24, 2021
A Simple kotlin first EventBus implementation

EventBus Simple event bus for event-driven programming. Taking advantage of kotlin language features instead of typical reflections Table of Contents

Zarzel K. Shih 4 Oct 14, 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 bus for Android and Java that simplifies communication between Activities, Fragments, Threads, Services, etc. Less code, better quality.

EventBus EventBus is a publish/subscribe event bus for Android and Java. EventBus... simplifies the communication between components decouples event s

Markus Junginger 24.2k Jan 7, 2023
eventbus-intellij-plugin 3.8 0.0 L1 Java Plugin to navigate between events posted by EventBus.

eventbus-intellij-plugin Plugin to navigate between events posted by EventBus. Post to onEvent and onEvent to Post Install There are two ways. Prefere

Shinnosuke Kugimiya 315 Aug 8, 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
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
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
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
Activities, Intents, Fragments e o componente de navegação - Kotlin - Android Studio

Words App This folder contains the source code for the Words app codelab. Introduction Words app allows you to select a letter and use Intents to navi

Ademir Oliveira 0 Nov 23, 2021
Criação de um App de Dicionário dividido em duas etapas utilizando Activities, Intents, Fragments e o componente de navegação

Words App This folder contains the source code for the Words app codelab. Introduction Words app allows you to select a letter and use Intents to navi

Lucas Caetano 1 Nov 22, 2021
An android application that provides simple communication between bluetooth enabled devices using LoRa for intermidiate data transfer

LoRa and bluetooth communication An android application that provides simple communication between bluetooth enabled devices using LoRa for intermidia

Erling Mathias Staff 2 May 4, 2022
Type safe intent building for services and activities

#IntentBuilder Type safe intent building for services and activities. IntentBuilder is a type safe way of creating intents and populating them with ex

Emil Sjölander 348 Oct 10, 2022
FragmentTransactionExtended is a library which provide us a set of custom animations between fragments.

FragmentTransactionExtended FragmentTransactionExtended is a library which provide us a set of custom animations between fragments. FragmentTransactio

Antonio Corrales 1.1k Dec 29, 2022
Asynchronous socket, http(s) (client+server) and websocket library for android. Based on nio, not threads.

AndroidAsync AndroidAsync is a low level network protocol library. If you are looking for an easy to use, higher level, Android aware, http request li

Koushik Dutta 7.3k Jan 2, 2023
FileLogger - a library for saving logs on Files with custom-formatter on background I/O threads, mobile-ready, android compatible,

The FileLogger is a library for saving logs on Files with custom-formatter on background I/O threads, mobile-ready, android compatible, powered by Java Time library for Android.

Abolfazl Abbasi 12 Aug 23, 2022