简体   繁体   English

是什么触发LiveData onChanged()?

[英]What triggers LiveData onChanged()?

I'm using Room and in the Dao I have this method: 我正在使用Room ,在Dao我有以下方法:

LiveData<List<Books>> getAllBooks();

In MainActivity I have subscribed to that method from the ViewModel . 在MainActivity中,我已从ViewModel订阅了该方法。 Changes to the data trigger the onChanged() callback: 更改数据将触发onChanged()回调:

    viewModel.getAllBooks()
            .observe(this, books -> {
                Log.d(TAG, "onChanged()");
                booksListAdapter.setData(new ArrayList<>(books));
            });

What I would like to know is what constitutes an update? 我想知道什么是更新? When the app first starts I do 100 insertions, each of them changes the database but the onChanged() is not invoked 100 times. 当应用程序首次启动时,我会进行100次插入,每个插入都会更改数据库,但是onChanged()不会被调用100次。 Last time I checked it called onChanged() the first time which I think it always calls when starting and then two more calls. 上一次我检查它第一次调用onChanged()时,我认为它总是在启动时调用,然后再调用两次。

Can I have control over this? 我可以对此进行控制吗? For example if I know I will be doing 100 insertions perhaps it would be better if I only got the callback at the end of the insertions. 例如,如果我知道将要进行100次插入,那么如果仅在插入结束时获得回调,那会更好。

You don't have control of that. 您对此无能为力。 What you can do is use MediatorLiveData and post the value after all insertions. 您可以做的是使用MediatorLiveData并在所有插入后发布该值。 Whenever you update, delete or insert Room knows that there has been change but doesn't know what has been changed. 每当您进行更新,删除或插入时,Room都会知道有更改,但不知道更改了什么。 So it just re-queries and sends the results to observing LiveData 因此,它只是重新查询并将结果发送给观察LiveData

Check this blog and mainly section 7. Avoid false positive notifications for observable queries . 查看此博客 ,主要查看第7部分。避免出现可观查询的误报 Author gives pretty good example of MediatorLiveData which is similar to what you are looking for 作者提供了一个很好的MediatorLiveData示例,它与您正在寻找的相似

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM