您的位置:首页 > 其它

模块间通信EventBus

2016-04-01 10:34 417 查看

模块间通信EventBus

1、简述

在真实项目中,模块之间需要通信的业务场景非常常见。比如:个人中心页面显示头像,但是在更改头像的页面更改头像之后,个人中心页面的头像要同步更新。

模块之间的通信可以通过:接口回调、广播、第三方框架EventBus。

接口回调:耦合性高,如果接口多了,不利于后期的维护,可能过几个月之后代码连自己都不想看了,回调地狱。

广播:广播是系统内置的组件,消息型组件,可以通过发送接收消息的形式实现通信,但太麻烦。

EventBus:底层采用反射的机制,使用简单,相比上面两种,代码可读性较高

项目地址:EventBus

2、代码示例

①、在gradle中配置引用:

compile 'org.greenrobot:eventbus:3.0.0'
②、单例封装EventBus,方便协调整个系统
public class EventBusManager {

private static EventBusManager busManager;
private EventBus globalEventBus;

private EventBusManager() {
}

public EventBus getGlobaEventBus() {
if (globalEventBus == null) {
globalEventBus = new EventBus();
}
return globalEventBus;
}

public static EventBusManager getInstance() {
if (busManager == null) {
synchronized (EventBusManager.class) {
if (busManager == null) {
busManager = new EventBusManager();
}
}
}
return busManager;
}
}
③、在更新完头像之后post事件
EventInformationUpadate event = new EventInformationUpadate();
EventBusManager.getInstance().getGlobaEventBus().post(event);
④、在个人中心页面注册EventBus监听
//在页面可视状态下注册监听
EventBusManager.getInstance().getGlobaEventBus().register(this);
//在页面不可视状态下取消注册监听
EventBusManager.getInstance().getGlobaEventBus().unregister(this);
/**
* EventBus的同步
*
* @param event 约定的event
*/
public void onEventMainThread(EventInformationUpadate event) {
//更新用户头像的逻辑
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息