EventBus框架提炼总结

来源:互联网 发布:看宝宝舌头知健康图解 编辑:程序博客网 时间:2024/06/10 01:43

1、EventBus:事件总线框架;用于组件之间的通信,实现解耦合;


2、下载地址:https://github.com/greenrobot/EventBus


3、用法:

a、注册:

 EventBus.getDefault().register(this);

b、注销

 EventBus.getDefault().unregister(this);

C、发布

EventBus.getDefault().post(value);

d、订阅:以onEvent开头的代表订阅事件


onEventMainThread 方法会在UI线程执行

onEventPostThread 方法会在当前发布事件的线程执行

BackgroundThread  方法如果在非UI线程发布的事件,则直接执行,和发布在同一个线程中。如果在UI线程发布的事件,则加入后台任务队列,使用线程池一个接一个调用。

Async 加入后台任务队列,使用线程池调用,异步执行。

eg.

public void onEventMainThread(String value){        if(value !=null){            tv.setText(value);//直接更新UI        }    }


4、原理

(1)EventBus是单例;使用EventBus.getDefault()获取;

(2)注册register时遍历当前类及其父类;将onEvent开头的、只有一个参数的Public方法遍历出来存入Map,参数为key,方法为value;

(3)发布post时根据参数遍历Map,得到方法名;

(4)使用反射执行方法;


参考资料:http://blog.csdn.net/lmj623565791/article/details/40920453


0 0
原创粉丝点击