EventBus
(2) 支持事件优先级定义,支持优先级高的订阅者取消事件继续传递,支持粘性事件,是不是跟系统的有序广播、粘性广播很像啊
(3) 不是基于 annotations
(4) 性能更优
(5) 体积小
(6) 支持单例创建或创建多个对象
(7) 支持根据事件类型订阅
EventBus is a publish/subscribe event bus for Android and Java.
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
Define events:
public static class MessageEvent { /* Additional fields if needed */ }
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); }
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.
Android projects:
implementation("org.greenrobot:eventbus:3.3.1")
Java projects:
implementation("org.greenrobot:eventbus-java:3.3.1")
<dependency>
<groupId>org.greenrobot</groupId>
<artifactId>eventbus-java</artifactId>
<version>3.3.1</version>
</dependency>
R8, ProGuard
If your project uses R8 or ProGuard this library ships with embedded rules.
Homepage, Documentation, Links
For more details please check the EventBus website. Here are some direct links you may find useful:
License
Copyright (C) 2012-2021 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.