当前位置:   article > 正文

EventBus : No subscribers registered for event class

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







声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/251139
推荐阅读
相关标签
  

闽ICP备14008679号