android - 为什么 LiveData 还要通知处于 onPause 状态的 Activity?

标签 android android-architecture-components android-livedata

我在Activity中有以下代码

@Override
public void onPause() {
    super.onPause();

    if (isFinishing()) {
        final LiveData<StickyNoteConfig> stickyNoteConfigLiveData = StickyNoteConfigRepository.INSTANCE.getStickyNoteConfig(mAppWidgetId);
        stickyNoteConfigLiveData.removeObservers(this);
        stickyNoteConfigLiveData.observe(this, stickyNoteConfig -> {
            // Weird, I still can receive call back.
            // I thought "this" is no longer active?
        });
    }
}

疑惑的是,虽然thisactivity已经处于onPause状态,但是Observer还在被触发?根据https://developer.android.com/reference/android/arch/lifecycle/Lifecycle.State#STARTED

Started state for a LifecycleOwner. For an Activity, this state is reached in two cases:

after onStart call;
right before onPause call.

请问为什么会这样?

最佳答案

According to LiveData reference,

  1. LiveData is a data holder class that can be observed within a given lifecycle. This means that an Observer can be added in a pair with a LifecycleOwner, and this observer will be notified about modifications of the wrapped data only if the paired LifecycleOwner is in active state. LifecycleOwner is considered as active, if its state is STARTED or RESUMED.

  2. An observer added with a Lifecycle will be automatically removed if the corresponding Lifecycle moves to DESTROYED state.

现在,根据您的情况,LiveDataonPause()observer(您的 Activity ) 中接收更新/strong> 方法,因为您的观察者尚未处于 DESTROYED 状态。

因此 LiveData 仍处于 Activity 状态以根据这些方法接收更新:

onActive() :

当活跃观察者的数量从 0 变为 1 时调用。 此回调可用于了解正在使用此 LiveData,因此应保持最新。

&

onInactive() :

当 Activity 观察者的数量从 1 变为 0 时调用。这并不意味着没有观察者,可能仍然存在观察者,但它们的生命周期状态不是 STARTED 或 RESUMED (就像 Activity返回堆栈)

可以通过hasObservers()查看是否有观察者.


那么 观察者(您的 Activity ) 何时进入DESTROYED 状态?

对于 LifeCycleOwner 的默认实现,表示 Activity 在 onDestroy() 方法执行后以及在 onPause() 它遵循 LifeCycle 状态的相反顺序 RESUMED -> STARTED -> CREATED -> DESTROYED

检查这个lifecycle graph .

希望对您有所帮助!

关于android - 为什么 LiveData 还要通知处于 onPause 状态的 Activity?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52617325/

相关文章:

android - 列出连接的蓝牙设备?

android - 将自定义 View 添加到工具栏

android - 使用 LiveData 而不是常规回调有什么好处吗?

android - 通过 intents 传递大量数据时崩溃 - extras 包是否有大小限制?

android - Robolectric + JMockIt 设置

android - 用 MutableLivedata<Cursor> 替换 getLoaderManager().initLoader

android-architecture-components - 在导航组件的起始目标位置时如何处理后退按钮

android - 在不使用 Room 的情况下使用 LiveData 和 ViewModel

android - Google SignInButton 的 onClick 无法使用数据绑定(bind)

android - 如何对LiveData转换进行单元测试