EventBus : No subscribers registered for event class

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


例如:

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

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

情况3:生命周期的问题

官方推荐是这样写:

https://github.com/greenrobot/EventBus

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

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

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


@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里面带过去







  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值