之前做图片社交App的时候,需要处理一个点赞数据的同步,比如在作品的详情页点赞 需要同时更新列表页该作品的点赞数量,这里还是以此为例。
compile 'org.greenrobot:eventbus:3.0.0'
public class DataSynEvent {
private int count;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
订阅
EventBus.getDefault().register(this);//订阅
解除订阅
EventBus.getDefault().unregister(this);//解除订阅
EventBus.getDefault().post(new DataSynEvent());
@Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
public void onDataSynEvent(DataSynEvent event) {
Log.e(TAG, "event---->" + event.getCount());
}
1
2
3
4
@Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
public void onDataSynEvent(DataSynEvent event) {
Log.e(TAG, "event---->" + event.getCount());
}
事件的优先级类似广播的优先级,优先级越高优先获得消息
@Subscribe(threadMode = ThreadMode.MAIN,priority = 100) //在ui线程执行 优先级100
public void onDataSynEvent(DataSynEvent event) {
Log.e(TAG, "event---->" + event.getCount());
}
发送有序广播可以终止广播的继续往下传递,EventBus也实现了此功能
EventBus.getDefault().cancelEventDelivery(event) ;//优先级高的订阅者可以终止事件往下传递
-keepattributes *Annotation*
-keepclassmembers class ** {
@org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }
# Only required if you use AsyncExecutor
-keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent {
<init>(java.lang.Throwable);
}