首页 > 学院 > 开发设计 > 正文

EventBus : No subscribers registered for event class

2019-11-08 00:17:15
字体:
来源:转载
供稿:网友

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

例如:

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

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

情况3:生命周期的问题

官方推荐是这样写:

https://github.com/greenrobot/EventBus

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

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

@OverridePRotected void onStart() {    super.onStart();    EventBus.getDefault().register(this);}@Overrideprotected 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里面带过去


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表