简体   繁体   English

Android EventBus和组件生命周期

[英]Android EventBus and Component LifeCycle

I am new to EventBus and was wondering what happens if the receiving party, an activity for example, gets destroyed or becomes null. 我是EventBus的新手,我想知道如果接收方(例如一项活动)被破坏或为空,会发生什么情况。 Please I need an explanation for this as am trying to build standards for building (architecting) android application and EventBus is the way I am using to decouple the components. 请在尝试构建用于构建(架构)android应用程序的标准时对此进行解释,EventBus是我用来分离组件的方式。

You should register any receiver when it should start receiving events and unregister it from receiving events when it shouldn't (eg going to be destoyed). 您应该在接收器应开始接收事件时对其进行注册,并在不应该接收其事件的情况下(例如,将其存储)取消注册。 In case of Activity / Fragment you should consider lifecycle methods like onCreate / onDestroy and onResume / onPause as the main lifecycle method pairs. 如果是Activity / Fragment ,则应将诸如onCreate / onDestroyonResume / onPause类的生命周期方法视为主要的生命周期方法对。

If you won't unregister the receiver from receiving events when it's going to be destroyed, then, depending on the actual event bus you are using you will either waste some amount of memory (for holding a null reference in the receivers map) or get the NPE (if event bus implementation doesn't check the receiver for null ). 如果在销毁接收器时不会取消其接收事件的注册,那么根据所使用的实际事件总线,您将浪费一些内存(用于在接收器映射中保留null引用)或获取NPE(如果事件总线实现未检查接收器的null )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM