在Applicationclass订阅Eventbus有什么缺点?

What are the disadvantages of subscribing to Eventbus in Application class?

我在 Android 应用程序中使用 EventBus。在我的 Application.onCreate() 中做一个 Eventbus.getDefault().register(this) 是个好主意吗?我没有任何 UI 更新要进行。我正在尝试这样做,以确保即使应用程序进入后台,我也能收到订阅数据。可能还有其他方法可以实现我想要的,但我很好奇这种方法是否有任何问题。

我的疑问是:

  1. 这会导致某种内存泄漏吗? Eventbus是在引用Application对象,而Application对象又是依赖Eventbus的。这看起来是循环的。

  2. 什么时候注销? Application.onTerminate() 不保证被调用。如果#1 不是问题,我想在应用程序 class.

  3. 中忽略退订就可以了

您的应用程序 class 将在应用程序物理停止时被终止。

这意味着:

  1. 当 OS 决定物理停止应用程序(可能需要几天时间)或有外部干预(即用户停止它或像 Clean Master 这样的实用程序应用程序),应用程序将被完全停止并销毁。
  2. 任何静态引用也将从内存中删除(即您的 EventBus 单例)。

(2) 将有效 只有 如果您正确注销您的听众,即在停止时注销 activity/fragment 或在 View.onDetachedFromWindow() 时注销视图,等等

只要在您的事件回调方法中您没有尝试 运行 单独线程中的某些内容或更新不存在的 activity/view/fragment,您应该没问题。

Will this cause some kind of memory leak ? Eventbus is referencing the Application object, and the Application object is also relying on Eventbus. This looks cyclic.

直接从应用程序订阅事件完全没问题class。 OS 将清理应用程序,而 EventBus 是其中的一部分。没问题。

When to unregister ? Application.onTerminate() is not guaranteed to be called. If #1 is not an issue, I guess it's fine to ignore unsubscribe in Application class.

是的,为了完整起见,我也会取消订阅 onTerminate。但是你是在 Android 设备上,如果清理了应用程序,那么一切都会消失,所以不需要 'clean up'.