前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >EventBus : No subscribers registered for event class

EventBus : No subscribers registered for event class

作者头像
wust小吴
发布2019-07-08 18:23:48
3.5K0
发布2019-07-08 18:23:48
举报
文章被收录于专栏:风吹杨柳

EventBus不适合向一个不存在于activity栈中的activity发送消息,这样是失败的,

例如:

情况1:一个activity 还没有生成,就post,肯定报这样的错;

情况2:一个activity曾经生成了,但是不在activity栈中了,也是收不到消息的

情况3:生命周期的问题

官方推荐是这样写:

https://github.com/greenrobot/EventBus

代码语言:javascript
复制
@Override
public void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}

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

而实际上这样不好,不应该在onStop里面就注销了,应该在onDestroy里面注销比较好

代码语言:javascript
复制
@Override
protected void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}

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

原因应该是:EventBus 是为已经存在的activity传递消息,而且订阅者必须要注册且不能被注销了,

如果你在onStop里面注销了,栈中虽然有这个activity,但是EventBus并没有被注册,所以也接收不到消息,

就报:No Subscribers registered 的问题

下面的话来自stackflow,很好:

In general, the EventBus is used to receive updated data for an already active activity or fragment. Think of the EventBus as more of a wrapper around an observer/consumer. For this example it looks like you are using it to pass data to another Activity.

所以有时候最好还是用标准的方法去传递相关的数据,比如bundle,在intent里面带过去

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017年02月24日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档