定义事件类型
public class FBBaseEvent {
public static final int START = 0x0;
public static final int LOADING = 0x10;
public static final int SUCCESS = 0x20;
public static final int FAIL = 0x30;
public int type;
public FBBaseEvent(int type) {
this.type = type;
}
}
public class FBEvent {
public static class Login extends FBBaseEvent {
public Login(int type) {
super(type);
}
}
}
使用步骤说明
/**
* Registers the given subscriber to receive events. Subscribers must call {@link #unregister(Object)} once they
* are no longer interested in receiving events.
*
* Posts the given event to the event bus.
*
* Subscribers have event handling methods that are identified by their name, typically called "onEvent". Event
* handling methods must have exactly one parameter, the event. If the event handling method is to be called in a
* specific thread, a modifier is appended to the method name. Valid modifiers match one of the {@link ThreadMode}
* enums. For example, if a method is to be called in the UI/main thread by EventBus, it would be called
* "onEventMainThread".
*/
注册(一般使用在Activity和Fragment)
EventBus.getDefault().register(this);
销毁(一般使用在Activity和Fragment)
EventBus.getDefault().unregister(this);
发送事件(一般使用在Presenter)
EventBus.getDefault().post(new FBEvent.Login(FBEvent.Login.LOADING));
EventBus.getDefault().post(new FBEvent.Login(FBEvent.Login.SUCCESS));
处理操作(一般使用在Activity和Fragment)
public void onEventMainThread(FBEvent.Login event) {
switch (event.type) {
case FBEvent.Login.START:
//处理操作
break;
case FBEvent.Login.SUCCESS:
//处理操作
break;
case FBEvent.Login.FAIL:
//处理操作
break;
}
}
总结:EventBus比较常用于MVP设计模式中。
参考资料:(建议按顺序查看)
1.官方
2.Android解耦库EventBus的使用和源码分析
网友评论