EventBus Features

What makes greenrobot’s EventBus unique, are its features:

  • Simple yet powerful: EventBus is a tiny library with an API that is super easy to learn. Nevertheless, your software architecture may great benefit by decoupling components: Subscribers do not have know about senders, when using events.
  • Battle tested: EventBus is one of the most used Android libraries: thousands of apps use EventBus including very popular ones. Over a billion app installs speak for themselves.
  • High Performance: Especially on Android, performance matters. EventBus was profiled and optimized a lot; probably making it the fastest solution of its kind.
  • Convenient Annotation based API (without sacrificing performance): Simply put the @Subscribe annotation to your subscriber methods. Because of a build time indexing of annotations, EventBus does not need to do annotation reflection during your app’s run time, which is very slow on Android.
  • Android main thread delivery: When interacting with the UI, EventBus can deliver events in the main thread regardless how an event was posted.
  • Background thread delivery: If your subscriber does long running tasks, EventBus can also use background threads to avoid UI blocking.
  • Event & Subscriber inheritance: In EventBus, the object oriented paradigm apply to event and subscriber classes. Let’s say event class A is the superclass of B. Posted events of type B will also be posted to subscribers interested in A. Similarly the inheritance of subscriber classes are considered.
  • Zero configuration: You can get started immediately using a default EventBus instance available from anywhere in your code.
  • Configurable: To tweak EventBus to your requirements, you can adjust its behavior using the builder pattern.

Quickly Start

EventBus’ API is as easy as 1-2-3. Before we get started with the 3 basic steps, let’s add the EventBus depency to your Gradle script (make sure you are using the latest version):

 compile 'org.greenrobot:eventbus:3.0.0'

Step 1: Define events

Events are POJO (plain old Java object) without any specific requirements.

public class MessageEvent {
public final String message; public MessageEvent(String message) {
this.message = message;
}
}

Step 2: Prepare subscribers

Subscribers implement event handling methods (also called “subscriber methods”) that will be called when an event is posted. These are defined with the @Subscribe annotation. Please note that with EventBus 3 the method name can be chosen freely (no naming conventions like in EventBus 2).

// This method will be called when a MessageEvent is posted
@Subscribe
public void onMessageEvent(MessageEvent event){
Toast.makeText(getActivity(), event.message, Toast.LENGTH_SHORT).show();
} // This method will be called when a SomeOtherEvent is posted
@Subscribe
public void handleSomethingElse(SomeOtherEvent event){
doSomethingWith(event);
}

Subscribers also need to register and unregister themselves to the bus. Only while subscribers are registered, they will receive events. In Android, Activities and Fragments usually bind according to their life cycle:

@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
} @Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}

Step 3: Post events

Post an event from any part of your code. All currently registered subscribers matching the event type will receive it.

EventBus.getDefault().post(new MessageEvent("Hello everyone!"));

Delivery Threads (ThreadMode)

EventBus can handle threading for you: events can be posted in threads different from the posting thread. A common use case is dealing with UI changes. In Android, UI changes must be done in the UI (main) thread. On the other hand, networking, or any time consuming task, must not run on the main thread. EventBus helps you to deal with those tasks and synchronize with the UI thread (without having to delve into thread transitions, using AsyncTask, etc).

In EventBus, you may define the thread that will call the event handling method by using one of the four ThreadModes.

ThreadMode: POSTING

Subscribers will be called in the same thread posting the event. This is the default. Event delivery is done synchronously and all subscribers will have been called once the posting is done. This ThreadMode implies the least overhead because it avoids thread switching completely. Thus this is the recommended mode for simple tasks that are known to complete is a very short time without requiring the main thread. Event handlers using this mode should return quickly to avoid blocking the posting thread, which may be the main thread. Example:

// Called in the same thread (default)

@Subscribe(threadMode = ThreadMode.POSTING) // ThreadMode is optional here
public void onMessage(MessageEvent event) {
log(event.message);
}

ThreadMode: MAIN

Subscribers will be called in Android’s main thread (sometimes referred to as UI thread). If the posting thread is the main thread, event handler methods will be called directly (synchronously like described for ThreadMode.POSTING). Event handlers using this mode must return quickly to avoid blocking the main thread. Example:

// Called in Android UI's main thread
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessage(MessageEvent event) {
textField.setText(event.message);
}

ThreadMode: BACKGROUND

Subscribers will be called in a background thread. If posting thread is not the main thread, event handler methods will be called directly in the posting thread. If the posting thread is the main thread, EventBus uses a single background thread that will deliver all its events sequentially. Event handlers using this mode should try to return quickly to avoid blocking the background thread.

// Called in the background thread
@Subscribe(threadMode = ThreadMode.BACKGROUND)
public void onMessage(MessageEvent event){
saveToDisk(event.message);
}

ThreadMode: ASYNC

Event handler methods are called in a separate thread. This is always independent from the posting thread and the main thread. Posting events never wait for event handler methods using this mode. Event handler methods should use this mode if their execution might take some time, e.g. for network access. Avoid triggering a large number of long running asynchronous handler methods at the same time to limit the number of concurrent threads. EventBus uses a thread pool to efficiently reuse threads from completed asynchronous event handler notifications.

// Called in a separate thread
@Subscribe(threadMode = ThreadMode.ASYNC)
public void onMessage(MessageEvent event){
backend.send(event.message);
}

References

Delivery Threads (ThreadMode)Open Source by greenrobot

Android EventBus实战 没听过你就out了 - Hongyang - 博客频道 - CSDN.NET

快速Android开发系列通信篇之EventBus - AngelDevil - 博客园

Android EventBus源码解析 带你深入理解EventBus - Hongyang - 博客频道 - CSDN.NET

EventBus学习入门的更多相关文章

  1. 每天成长一点---WEB前端学习入门笔记

    WEB前端学习入门笔记 从今天开始,本人就要学习WEB前端了. 经过老师的建议,说到他每天都会记录下来新的知识点,每天都是在围绕着这些问题来度过,很有必要每天抽出半个小时来写一个知识总结,及时对一天工 ...

  2. C# BackgroundWorker组件学习入门介绍

    C# BackgroundWorker组件学习入门介绍 一个程序中需要进行大量的运算,并且需要在运算过程中支持用户一定的交互,为了获得更好的用户体验,使用BackgroundWorker来完成这一功能 ...

  3. 给深度学习入门者的Python快速教程 - 番外篇之Python-OpenCV

    这次博客园的排版彻底残了..高清版请移步: https://zhuanlan.zhihu.com/p/24425116 本篇是前面两篇教程: 给深度学习入门者的Python快速教程 - 基础篇 给深度 ...

  4. 给深度学习入门者的Python快速教程 - numpy和Matplotlib篇

    始终无法有效把word排版好的粘贴过来,排版更佳版本请见知乎文章: https://zhuanlan.zhihu.com/p/24309547 实在搞不定博客园的排版,排版更佳的版本在: 给深度学习入 ...

  5. UML学习入门就这一篇文章

    1.1 UML基础知识扫盲 UML这三个字母的全称是Unified Modeling Language,直接翻译就是统一建模语言,简单地说就是一种有特殊用途的语言. 你可能会问:这明明是一种图形,为什 ...

  6. Stanford Parser学习入门(2)-命令行运行

    在Stanford parser目录中已经定义了一部分命令行工具以及图形界面,本文将介绍如何在windows使用这些工具进行语法分析,Linux下也有shell可以使用. 关于如何搭建环境请参考上一篇 ...

  7. Python学习入门基础教程(learning Python)--5.6 Python读文件操作高级

    前文5.2节和5.4节分别就Python下读文件操作做了基础性讲述和提升性介绍,但是仍有些问题,比如在5.4节里涉及到一个多次读文件的问题,实际上我们还没有完全阐述完毕,下面这个图片的问题在哪呢? 问 ...

  8. 深度学习入门实战(二)-用TensorFlow训练线性回归

    欢迎大家关注腾讯云技术社区-博客园官方主页,我们将持续在博客园为大家推荐技术精品文章哦~ 作者 :董超 上一篇文章我们介绍了 MxNet 的安装,但 MxNet 有个缺点,那就是文档不太全,用起来可能 ...

  9. Shell脚本编程学习入门 02

    Shell脚本编程学习入门是本文要介绍的内容,我们可以使用任意一种文字编辑器,比如gedit.kedit.emacs.vi等来编写shell脚本,它必须以如下行开始(必须放在文件的第一行):   #! ...

随机推荐

  1. ion-slide-box,无限循环

    ion-slide-box网络加载图片,及时更新,无限循环 does-continue:是否循环切换,开头的幻灯页只能向左滑动,最后的幻灯页只能向右滑动. 将does-continue属性值设为tru ...

  2. [codevs1155][KOJ0558][COJ0178][NOIP2006]金明的预算方案

    [codevs1155][KOJ0558][COJ0178][NOIP2006]金明的预算方案 试题描述 金明今天很开心,家里购置的新房就要领钥匙了,新房里有一间金明自己专用的很宽敞的房间.更让他高兴 ...

  3. word20161130

    1. even 偶数 [ǒu shù][词典] even; [数] even number;[例句]在本例中,slot A中有奇数个阵列,slot B中有偶数个阵列.In this example, ...

  4. C#面向对象思想计算两点之间距离

    题目为计算两点之间距离. 面向过程的思维方式,两点的横坐标之差,纵坐标之差,平方求和,再开跟,得到两点之间距离. using System; using System.Collections.Gene ...

  5. UML统一建模编程

    PowerDesigner 可以通过类图直接可视化生成代码 UML模型元素: 表示模型中的某个概念(类.对象.用例.结点.组件.包.接口等等): 表示模型间相互连接的关系(关联.泛化.依赖.聚集).

  6. php5.3 appache phpstudy win7win8win10下 运行速度慢解决办法

         在部署服务器以及本地测试的时候发现了一个奇怪的现象,运行PHP程序的时候非常慢,起先以为是网速的原因,后经本地测试发现速度依旧非常慢,打开一个页面差不多要用时3秒以上,这肯定是不正常的,因为 ...

  7. 调用pyxmpp库PyQt编程打包成exe文件出错

    pyxmpp库内resolver.py内getaddrinfo获取Openfire服务器地址出错

  8. linux 终端报错 Out of memory: Kill process[PID] [process name] score问题分析

    从Out of memory来看是内存超出了,后面的 Kill process[PID] [process name] score好像和进程有关了,下面我们就一起来看看linux 终端报错 Out o ...

  9. NFV技术中遇到的新名词

    NUMA topology:Non-Uniform Memory Access (NUMA) is a computer system architecture that is used with m ...

  10. [20160731][转]JAVA当中变量什么时候需要初始化

    1. 对于类的成员变量,不管程序有没有显式的进行初始化,Java虚拟机都会先自动给它初始化为默认值. 默认值如下:             Boolean      false             ...