Miso Piso
Miso Piso

Reputation: 171

Room + LiveData change query function dynamically

I'm making an app that should update the current list. Implementation is done using room and livedata, I'm using the mvp pattern without viewmodel. My question is, if I have a query that returns all items in selected category and I have an observable already on the livedata, can I change the dao function with different query parameters and update the list accordingly. The closest thing to it I have found is: Android Room LiveData select query parameters

But as I'm relatively new to development and am currently exploring the reactive paradigm in android, this has proven quite a challenge.

in presenter

override var itemsList: LiveData<List<Item>?> = 
itemDao.getItemsForCategory(1)

in mainAcivity

presenter.itemsList.observe(this, Observer {
    if (it != null) {
        itemAdapter.setTodoItems(it)
        itemListHolder.adapter =itemAdapter
    }
})

in dao

@Query("SELECT * FROM Item")
fun getItemsFromDatabase(): LiveData<List<Item>?>

@Query("SELECT * FROM Item WHERE category_id == :category_id ORDER BY 
creationTime ASC")
fun getItemsForCategory(category_id: Long): LiveData<List<Item>?>

EDIT (solution)

the solution was mutableLiveData in which the value changes the query parameters:

override var itemsList: LiveData<List<IItem>?> = Transformations.switchMap(mutableLiveData) {
    itemDao.getItemsForCategory(mutableLiveData.value!!.toLong())
}

override fun onItemsCalled(categoryId: Long) {
    when (mutableLiveData.value) {
        1 -> mutableLiveData.value = 2
        2 -> mutableLiveData.value = 3
        3 -> mutableLiveData.value = 4
        4 -> mutableLiveData.value = 1
    }
}

this is just a query for the same category, but with different handling anything is possible.

Upvotes: 5

Views: 2274

Answers (1)

Miso Piso
Miso Piso

Reputation: 171

EDIT (solution)

the solution was mutableLiveData in which the value changes the query parameters:

override var itemsList: LiveData<List<IItem>?> = Transformations.switchMap(mutableLiveData) {
itemDao.getItemsForCategory(mutableLiveData.value!!.toLong())
}

override fun onItemsCalled(categoryId: Long) {
    when (mutableLiveData.value) {
        1 -> mutableLiveData.value = 2
        2 -> mutableLiveData.value = 3
        3 -> mutableLiveData.value = 4
        4 -> mutableLiveData.value = 1
    }
}

Upvotes: 7

Related Questions