美文网首页
[了解点皮毛] EventBus的简单使用

[了解点皮毛] EventBus的简单使用

作者: HiSea | 来源:发表于2016-03-21 17:59 被阅读0次

    定义事件类型

    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的使用和源码分析

    相关文章

      网友评论

          本文标题:[了解点皮毛] EventBus的简单使用

          本文链接:https://www.haomeiwen.com/subject/sibklttx.html