Best practice: Runtime filters with Room and LiveData

后端 未结 3 437
傲寒
傲寒 2021-02-02 11:24

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

3条回答
  •  猫巷女王i
    2021-02-02 11:42

    So, I ended up doing it like this:

    • The fragment fowards the filter state to the ViewModel. Side effect: the filter state may be used by multiple (i.e. subsequent due to configuration change) fragment instances. Maybe you want that, maybe not. I do.
    • The ViewModel holds a MediatorLiveData instance. It has a single source: The Room DB LiveData object. The source simply forards changes to the mediator. If the filter is changed by the fragment, the source is swapped by a requery.

    Answering my detailed questions:

    • No postfiltering
    • Yes, requery on filter change
    • I don't reuse the ComputableLiveData (not sure wether it would be possible)

    Regarding the discussion in the comments:

    • I don't apply paging

    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.

    EDIT: 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.

    Thanks to CommonsWare and pskink for your help!

提交回复
热议问题