android - 即使数据没有变化,LiveData 观察者的 onChanged 也会在 Activity 轮换时被调用

标签 android viewmodel android-livedata

我在 Android 应用程序中使用 ViewModelsLiveData,我想使用它们跟踪 Activity 的数据,即使在屏幕旋转时也是如此.这很好用,但有一个问题我无法解决。在 Activity 的 onCreate 方法中,我为包含对象列表的 LiveData 注册了一个观察者,如果加载了数据,它应该只向 Activity 添加一个 Fragment。然后,我仅在 savedInstanceState 为 null 时才重新加载数据,这应该会阻止它在屏幕旋转时重新加载。这看起来像这样:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        model = ViewModelProviders.of(this).get(MainActivityModel.class);
        observeList();
        if (savedInstanceState == null) {
            loadList(); //Reload the list and call postValue() on the LiveData.
        }
    }

    private void observeList() {
        model.getList().observe(this, new Observer<ArrayList<Object>>(){
            @Override
            public void onChanged(@Nullable ArrayList<Object> objects) {
                //Add list fragment whenever data changes.
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.container, ListFragment.getInstance(list))
                        .commit();
            }
        });
    }

按照我的理解,ListFragment 只应在数据更改时显示。但是,经过一些调试,似乎每次旋转屏幕时都会调用 observeList 方法中的 onChanged 方法。此外,我检查了实际列表是否已更改并且它完全相同,完全没有区别,甚至没有 postValue() 或 setValue() 方法调用.因此,我不知道为什么会在屏幕旋转时调用 onChanged 方法。

这也只有当列表包含某些内容时才会发生。启动应用程序时,在调用 loadList() 之前列表的长度为 0。在此状态下注册观察者时,不会调用onChanged方法。

我最好的猜测是 onChanged 方法被触发是因为当观察者注册时列表不为空,所以观察者可能认为数据发生了变化。谁能解释为什么会发生这种情况?

最佳答案

这是按预期工作的。来自 livedata overview :

To ensure that the activity or fragment has data that it can display as soon as it becomes active. As soon as an app component is in the STARTED state, it receives the most recent value from the LiveData objects it’s observing. This only occurs if the LiveData object to be observed has been set.

虽然缺少代码 fragment - loadList 应该是 ViewModel 本身的一部分,而不是 Activity 方法。

关于android - 即使数据没有变化,LiveData 观察者的 onChanged 也会在 Activity 轮换时被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54592866/

相关文章:

asp.net-mvc - 如何处理具有多个聚合根的 View 模型?

android - 组合两个具有相同观察者类型的 LiveData 对象

安卓房间 : Handling Relations with LiveData

java - AAR 传递依赖 Google 位置服务

Android 可选 GPS 权限

android - 如何放大 Android 图像而不使其模糊?

android - 设置棕褐色时 setParameters 失败,但缩放效果很好

asp.net-mvc - 如何在 ASP.NET MVC 中捕获 g-recaptcha-response?

wpf - MVVM - 控件与 View

android - 导航 Controller 在实时数据观察器中被调用两次