EventBus使用问题

来源:互联网 发布:手机淘宝退款售后 删除 编辑:程序博客网 时间:2024/06/03 16:09

EventBus使用问题

EventBus没搞清楚,就用在项目上了,结果出了很多问题,尤其是postSticky的时候。
这是注册的时候:

@Override    protected void onStart() {        super.onStart();        if (!EventBus.getDefault().isRegistered(this))            EventBus.getDefault().register(this);    }    @Override    protected void onDestroy() {        if (EventBus.getDefault().isRegistered(this))            EventBus.getDefault().unregister(this);        super.onDestroy();    }

使用postSticky的时候复用了很多的Event,后来发现才postSticky,上一界面还没有刷新的时候,以前有的界面已经消费了,如果你是ViewPage+Fragment,那就更难受了。解决方案,第一种,不要在onStart,onDestroy中注册和反注册,可以在onResume, onPause中, 这种情况不适用ViewPage Add 多个相同Fragment,在fragment中注册。第二种,在一条逻辑线上,最好每种事件最好自建一个event的,不要交叉消费了。
ViewPage+Fragment:

 @Override    public void onResume() {        super.onResume();        if (!EventBus.getDefault().isRegistered(this))            EventBus.getDefault().register(this);    }    @Override    public void onPause() {        if (EventBus.getDefault().isRegistered(this))            EventBus.getDefault().unregister(this);        super.onPause();    }    @Subscribe(sticky = true)    public void getBackInfo(XXX event) {            XXXxx  child = (XXXxx) fragmentLst.get(vp.getCurrentItem());            child.refreshPage();            EventBus.getDefault().removeAllStickyEvents();        }    }
0 0
原创粉丝点击