是否有任何保证的方法来模仿正在重新创建的 activity 的 `onDestroy()` 和 `onCreate()` 方法之间的某些操作?

Is there any guarenteed way to mimic some action between `onDestroy()` and `onCreate()` methods of an activity being recreated?

Here 我写了一个 MutableLiveList<T> class 来代替我项目中的 MutableLiveData<MutableList<T>>。到现在为止一切正常。但是,如果在 activity 处于非活动状态时对列表进行了多次修改,则只有对该列表的最后一次修改才会触发适配器通知方法。在这种情况下,我不知道应用程序是否会崩溃。所以我需要准确地模仿那种情况。当屏幕旋转时,activity 被销毁并重新创建。但我不知道如何在该间隔之间将项目添加到该列表。任何人都请帮助我。或者告诉我更好的方法。

您可以将它们添加到 activity 的 onDestroy 回调函数中。此时 activity 的 Lifecycle 对象处于 CREATEDDESTROYED 状态:

关键是它当时不在 STARTED 状态,and:

LiveData considers an observer, which is represented by the Observer class, to be in an active state if its lifecycle is in the STARTED or RESUMED state. LiveData only notifies active observers about updates. Inactive observers registered to watch LiveData objects aren't notified about changes.

因此,当您进入 onDestroy 时,任何使用 activity 的 Lifecycle 的观察者都不会看到来自 LiveData 的任何更新。因此,您应该能够在不收到通知的情况下向 LiveData 添加值。


顺便说一句,“只通知最后一个值”更新is by design:

Generally, LiveData delivers updates only when data changes, and only to active observers. An exception to this behavior is that observers also receive an update when they change from an inactive to an active state. Furthermore, if the observer changes from inactive to active a second time, it only receives an update if the value has changed since the last time it became active.

因此,如果观察者处于非活动状态时数据变为 A, B, C,则不会通知这些值。当它从非活动状态变为非活动状态时,它将获得最新值 C。它不会保存观察者错过的所有值的历史记录