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. Redis 读后小感

    经过一个多月的业余时间,终于把 Redis 完整的撸了一遍,感谢峰哥推荐的书<Redis 设计与实现>,也谢谢作者把 Redis 解析的这么通俗易懂. 去年 10 月末入职的某厂是 Red ...

  2. Linux 动态监听进程shell

    背景 前几天在研究线程的时候,看到一句话说java里的线程Thread.run都会在Linux中fork一个的轻量级进程,于是就想验证一下(笔者的机器是Linux的).当时用top命令的时候,进程总是 ...

  3. 【转】将datatable数据转化成list

    #region 将datatable数据转化成list   public static List<T> ToList<T>(this DataTable dt) where T ...

  4. maven项目如何使用jetty启动?

    1.在pom.xml文件中插入下面的片段 <build> <plugins> <plugin> <groupId>org.eclipse.jetty&l ...

  5. CSU 1333 Funny Car Racing (最短路)

    题目链接: http://acm.csu.edu.cn/OnlineJudge/problem.php?id=1333 解题报告:一个图里面有n个点和m条单向边,注意是单向边,然后每条路开a秒关闭b秒 ...

  6. hdu4747——Mex

    1.题目大意:对一个序列的每一个区间求Mex,最后所有的mex相加(mex就是SG的那个),力求nlogn... 2.分析:最近开始刷线段树了,还是有很多不会啊 首先把1-1 1-2 1-- 1-n这 ...

  7. Unity 视频播放杂谈

    http://www.cnblogs.com/zsb517/p/4060814.html 背景:      游戏机中想加入舞蹈元素,最先的想法是开发舞蹈游戏,然后通过动画来表现舞蹈,给用户提供舞蹈教学 ...

  8. [lintcode 14] First Position of Target

    For a given sorted array (ascending order) and a target number, find the first index of this number ...

  9. django的前后的结合,search搜索功能案例

    利用django的Q()功能可以很好的展开搜索功能 假设我要做个这样的搜索功能

  10. JQuery发送Ajax请求出现 500 Internal Server Error

    ajax返回,readyState=4,status=500,chrome f12提示,提示服务器内部错误 我采用 http://q.cnblogs.com/q/69745/的解决办法根本不行,也不是 ...