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. 用phpcms开发模块时中文乱码问题

    学着用phpcms开发一个文件管理模块,出现中文乱码,折腾了半天,总结如下 1.自己在mysql客户端建表,默认表格的编码为latin1_swedish_ci,虽然可以建好后用alter命令修改编码, ...

  2. 深入理解Java虚拟机之读书笔记一 自动内存管理机制

    一.运行时数据区域 1.程序计数器是线程的私有空间,每个线程都有.针对线程执行的是Java代码还是Native代码有两种取值,Java代码时:虚拟机字节码指令的地址:Native代码时:计数值为Und ...

  3. BZOJ2466——[中山市选]树

    1.题目大意:给你一棵树,树的每个节点都有一个权值,是0或1,最开始都是0,你可以做一种修改操作,就是把一个节点和它相邻的 节点的权值取反,问最少几次修改能把所有节点的权值变得都是1,最多100个节点 ...

  4. event相关

    event.button 事件属性可返回一个整数,指示当事件被触发时哪个鼠标按键被点击. event.keyCode  事件属性可返回一个整数,指示当事件被触发时哪个键盘按键被点击. <scri ...

  5. 关于在android 4.2.2 上运行runlmbench

    在剑锋的基础上加一些自己笔记,让自己更懂一些这个流程. 参考:http://www.cnblogs.com/zengjfgit/p/5731655.html runlmbench 是一款在linux ...

  6. linux下一步一步安装禅道项目管理工具

    linux下一步一步安装禅道项目管理工具 因为禅道官网的安装教程实在是太简陋了,所以记录在此. 1.安装apache服务 archlinux下直接 sudo pacman -S apache ubun ...

  7. QT国际化 一 (lupdate/linguits/lrelease)

    QT国际化(lupdate/linguits/lrelease) 本文由乌合之众瞎写http://www.cnblogs.com/oloroso/ qt国际化其实就是qt中字符串的字符集编码的设置.当 ...

  8. Python正则表达式汇总

    判断是否是整数或小数,在网上看到一个方法: type(eval(")) == int type(eval("123.23")) == float 后来又看到<Pyt ...

  9. 使用Gitosis搭建Git服务器

    使用Gitosis搭建Git服务器 作者: JeremyWei | 可以转载, 但必须以超链接形式标明文章原始出处和作者信息及版权声明 网址: http://weizhifeng.net/build- ...

  10. 谷歌chrome浏览器和火狐firefox浏览器自带http抓包工具和请求模拟插件

    谷歌chrome浏览器自带http抓包工具 chrome://net-internals/ 谷歌chrome浏览器http请求模拟插件:postman 火狐http请求模拟插件:httprequest ...