Eventbus3.0入(踩)门(坑)之旅

来源:互联网 发布:wow数据库 编辑:程序博客网 时间:2024/06/01 09:01

首先祭出eventbus gayhub地址!

第一步:
导包:compile ‘org.greenrobot:eventbus:3.0.0’
第二步:
需要一个class,它的作用就是接受传过来的信息,你可以理解成调用接口返回封装了数据的类

public class FirstEvent {    private String mMsg;    public FirstEvent(String msg) {        mMsg = msg;    }    public String getMsg(){        return mMsg;    }}  

第三步:
在你需要接受消息的地方来一个这个(其实就是订阅),这个地方sticky = true暂可忽略,后面说。

 @Subscribe(sticky = true,threadMode = ThreadMode.MAIN)    public void postingME(FirstEvent event){        Log.i("robin1", "postingME222: "+event.getMsg());    }

然后注册eventbus,比如在activity里面(这个地方可以抽取到baseactivity里面去,但是有坑,之后再说)

@Override public void onStart() {     super.onStart();     EventBus.getDefault().register(this); } @Override public void onStop() {     super.onStop();     EventBus.getDefault().unregister(this); }

第四步:
发送!注意,发送的数据类型要和Subscribe的方法的参数保持一致。

EventBus.getDefault().post(new FirstEvent("这是发送的文本111"));

上面就是官方介绍,说说使用场景吧,用过MVP模式的同学都知道,presenter拿到model的数据(其实就是接口返回的数据)之后,可以post出去,然后再view(activity)中接收,做一些UI的改变。
对,这是一般的情况,我突发奇想,两个activity之间传值可不可以?既然叫,事件总线,那么肯定是可以的,于是乎!
在activity1中post数据,在activity2中注册eventbus,解注册eventbus,然后,订阅方法。一气呵成,跑起来:wtf????怎么啥反应都没有?狂点,没用。

原来你post的时候,activity2还没加载,eventbus还没有注册,所以订阅也没用。解决方案就是:使用postSticky发送,然后把订阅的方法上面的注解加上sticky = true就行了。其实,这样还不如sratactivityforresult。

好了,开始踩坑:
坑1:Subscriber class com.android.myapplication.login.MainActivity and its super classes have no public methods with the @Subscribe annotation

可能你会碰到这样的一个bug.

看不清的有点,在新标签中查看

bug原因:你注册eventbus的地方,没有订阅的方法。
解决方案:加上订阅的方法。
其实你不加,这就违背了eventbus的设计,发送了,但是没有接受,那有啥用呢?

坑2: Subscriber class com.android.myapplication.login.MainActivity and its super classes have no public methods with the @Subscribe annotation
有人骂我了,这不是第一个坑吗?确实,错误信息一样。我们看一下原因
bug原因:这是因为你写了订阅方法,但是你的参数没写,也就是没有参数
解决方案:写上参数。
其实你想想,你不写参数,这是个啥?啥都不是。所以设计的时候还是给你报个错让你知道比较好。

坑3:Subscriber class com.android.myapplication.login.MainActivity already registered to event class com.android.myapplication.FirstEvent
bug原因:多次注册eventbus
解决方案:只能注册一次。
有人看到这,又要骂我了,玩呢??你傻逼写两句EventBus.getDefault().register(this);
大爷别急,确实任何人都不会连着写两句注册,除非马虎。但是,有一种情况,你们有baseactivity,你们的activity都继承于他,然后你又没仔细看baseactivity,然后你在activity里面注册了,也会导致这个问题,这个比较常见,尤其是新的项目二次开发的时候,这里我只是提一嘴,给大家提个醒。

好了现总结到这吧,后期用的过程中有bug的话,我会再更新。

阅读全文
1 0