EventBus 基础篇

来源:互联网 发布:韩国社交软件sns 编辑:程序博客网 时间:2024/06/06 03:07

最近在研究RxJava ,突然想起了事件分发另一个强大的框架Eventbus ,并且项目经常用到,特意整理了下。
what is Eventbus?
官方的解释为:
EventBus is a publish/subscribe event bus optimized for Android.
它是专门为优化安卓一个 发布者/订阅者的事件总线。

事件分发流程

发布者,发布事件。通过事件总线(其实就是在一个单例内部维持着一个map对象存储了一堆的方法),分发给订阅者。

它的优点:
轻量、简单、降低耦合。

用法:
1.声明Event事件

public class MessageEvent { /* Additional fields if needed */ }

2.注册

eventBus.register(this);

声明方法,有四种方法,最主要的是:

 @Subscribe    public void onEventMainThread(CommonEvent event) {    }

3.发布事件

eventBus.post(event);

例子:
在oncrete() 方法中注册,无论是Activity 还是Fragment ,不在这里注册会报错。

 @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        EventBus.getDefault().register(this);        btn=(Button)findViewById(R.id.btn);        tv=(TextView)findViewById(R.id.tv);        btn.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                Intent intent=new Intent(MainActivity.this,SecondActivity.class);                startActivity(intent);            }        });    }

在OnDestroy中反注册

  @Override    protected void onDestroy() {        super.onDestroy();        EventBus.getDefault().unregister(this);    }

声明订阅者:

 @Subscribe    public void onEventMainThread(CommonEvent event) {       if(event.getType().equals(CommonEvent.TYPE_99)){           tv.setText("从第二个页面来的:eventtype="+event.getType());       }    }

在需要触发事件的位置提交事件:例如我在第二个界面提交事件,在第一个页面接受:

 EventBus.getDefault().post(new CommonEvent(CommonEvent.TYPE_99));

代码并不难,希望通过我这个例子,一是巩固自己的学习和理解,二是希望更多的人更好的学习,我会再接再厉,写更多的博文。

源码下载

我的微信公众号:行走的那些事,欢迎大家扫一扫。
行走的那些事

0 0
原创粉丝点击