gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:34:02 48 4
gpt4 key购买 nike

我在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/

48 4 0