最佳实践:带有Room和LiveData的运行时筛选器 [英] Best practice: Runtime filters with Room and LiveData

查看:360
本文介绍了最佳实践:带有Room和LiveData的运行时筛选器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个屏幕,该屏幕显示了使用回收站的Room包装的DB的内容.适配器从ViewModel获取LiveData,该ViewModel隐藏对Room DAO对象的查询调用.因此,LiveData对象实际上是一个ComputableLiveData对象,它知道Room DB的更改.

I am working on a screen that shows the contents of a Room wrapped DB using a recycler. The adapter gets the LiveData from a ViewModel that hides the query call on the Room DAO object. So, the LiveData object is actually a ComputableLiveData object that is aware of changes to the Room DB.

现在,我想在屏幕上添加过滤器选项.在此Room-LiveData-ViewModel设置中,我将在哪里/如何实现它?

Now I want to add filter options to the screen. Where / how would I implement this in this Room-LiveData-ViewModel setup?

适配器或ViewModel是否应在LiveData中对结果进行后置过滤"?是否应针对每个过滤器更改从房间中重新查询数据?我可以为此重用基础的(可计算的)LiveData吗?如果没有,我是否真的应该为每个过滤器更改创建新的LiveData?

Should the adapter or ViewModel "postfilter" the results in the LiveData? Should I requery the data from room for every filter change? Can I reuse the underlying (Computable)LiveData for that? If not, should I really create new LiveData for every filter change?

此处讨论了类似的问题:重新加载RecyclerView使用Room,ViewModel和LiveData更改数据后

A similar question is discussed here: Reload RecyclerView after data change with Room, ViewModel and LiveData

推荐答案

所以,我最终这样做了:

So, I ended up doing it like this:

  • 该片段将过滤器状态转移到ViewModel.副作用:多个片段实例可能会使用过滤器状态(即由于配置更改而导致后续使用).也许您想要那样,也许不需要.我知道.
  • ViewModel包含一个MediatorLiveData实例.它只有一个来源:Room DB LiveData对象.消息源只是预示着要更改调解员.如果过滤器被片段更改,则源将被重新查询交换.

回答我的详细问题:

  • 不进行后过滤
  • 是的,重新查询过滤器更改
  • 我不会重用ComputableLiveData(不确定是否可以使用)

关于评论中的讨论:

  • 我不应用分页

关于会议室的最后说明:我错了吗?或者我需要为我要应用的每个过滤器组合编写单独的DAO方法吗?好的,我可以通过String插入select语句的可选部分,但是那样我会失去Room的好处.某种使语句可组合的语句生成器会很好.

Final note on Room: Am I wrong or do I need to write seperate DAO methods for every filter combination I want to apply? Ok, I could insert optional parts of the select statement via a String, but then I would lose the benefits of Room. Some kind of statement builder that makes statements composable would be nice.

请注意下面Ridcully的评论.他提到了SupportSQLiteQueryBuilder和@RawQuery来解决我猜的最后一部分.我还没有检查出来.

Please note the comment by Ridcully below. He mentions SupportSQLiteQueryBuilder together with @RawQuery to address the last part I guess. I didn't check it out yet though.

感谢 CommonsWare pskink 为您提供帮助!

这篇关于最佳实践:带有Room和LiveData的运行时筛选器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆