在EventBus的官方github中,定义为
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 (~50k jar)
- is proven in practice by apps with 100,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());
底层采用观察者模式
getdefault方法中,使用了双验证加锁的单例模式
EventBus简化了Android应用中组件间的通信,通过观察者模式实现事件发送者与接收者的解耦,优化了Activities、Fragments及后台线程的性能,避免复杂依赖和生命周期问题,使代码更简洁高效。
436

被折叠的 条评论
为什么被折叠?



