简体   繁体   English

事件总线在应用程序类中注册和取消注册

[英]Event Bus Register And Unregister in Application Class

Should i register and unregister the event bus in application class? 我应该在应用程序类中注册和注销事件总线吗? If yes then where should i register and unregister it? 如果是,那么我应该在哪里注册并取消注册?

Once Register of event bus is done in application class then should i need to register the event bus in suscriber class? 一旦事件总线的注册在应用程序类中完成,那么我是否需要在suscriber类中注册事件总线?

Is there any problem occurs if i put some methods in Application class as a suscriber methods? 如果我在Application类中添加一些方法作为suscriber方法,是否会出现任何问题?

No one, except you, can tell whether you should or shouldn't register Application as a listener on EventBus - it depends on your app's use cases. 除了你之外,没有人可以判断你是否应该将Application注册为EventBus上的监听器 - 这取决于你的应用程序的用例。

If the event is relevant to a specific Activity / Fragment / Service - register them as listeners. 如果事件与特定的Activity / Fragment / Service - 将它们注册为侦听器。

If the event is relevant in the "global" sense (ie centralized error handling based on events) - you might register Application as listener. 如果事件与“全局”意义相关(即基于事件的集中式错误处理) - 您可以将Application注册为侦听器。

You don't need to unregister Application from EventBus in order to prevent memory leaks because: 您不需要从EventBus取消注册Application以防止内存泄漏,因为:

  • their lyfe-cycles are identical ( Application can be treated as Singleton object) 他们的lyfe循环是相同的( Application可以被视为Singleton对象)
  • there is no onDestroy() method in Application Application没有onDestroy()方法

您可以创建一个具有onStart()和onStop()具体方法和eventbus实例的Common类,现在您可以在不需要时通过触发该类取消注册EventBus实例。

Subscribe in onStart() unsubscribe in onStop() or any other Android lifecycle component you wish to. 订阅onStart()取消订阅onStop()或您希望的任何其他Android生命周期组件。

You should be able to have instance of your Event Bus in subscriber class if it implements / extends it or has any instance of it in your class. 如果它实现/扩展它或在您的类中有任何实例,您应该能够在订阅者类中拥有您的事件总线的实例。

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

相关问题 在应用程序类中注册和取消注册BroadcastReceiver - Register and Unregister the BroadcastReceiver in Application Class 哪些Activity生命周期方法最适合注册/注销到事件总线? - Which Activity lifecycle methods are best to register/unregister to event bus? 事件总线片段取消注册 - Event Bus Fragment Unregister 哪个生命周期事件最适合注册/注销监听器? - Which lifecycle event is best to register/unregister listeners? 单击按钮如何注册或注销传感器事件侦听器? - How to register or unregister a sensor event listener on click of a button? 哪个生命周期事件是注册/注销位置侦听器的最佳位置? - Which lifecycle event is the best place to register/ unregister a location listener? 如何从应用程序类中注销广播接收器? - How to unregister broadcast receiver from an Application Class? 从应用程序 class 注销回调的正确方法 - Proper way to unregister a callback from an Application class Android-使用带有静态方法的Helper类动态注册/注销接收器? - Android - Register/Unregister Receiver Dynamically using a Helper Class with Static Methods? 何时为自定义View类注册/注销广播接收器? - When to register/unregister a Broadcast Receiver for a custom View class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM