5

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.

RandomEngy
  • 14,931
  • 5
  • 70
  • 113
Miso Piso
  • 161
  • 9
  • 4
    Possible duplicate of [Filling an adapter from different LiveData sources](https://stackoverflow.com/questions/54403479/filling-an-adapter-from-different-livedata-sources) – EpicPandaForce Feb 04 '19 at 17:37
  • Store the categoryId in a MutableLiveData, then you can switchMap the query against it. – EpicPandaForce Feb 04 '19 at 17:37
  • @EpicPandaForce yup, tnx for the input, i got it, it's working now, il post the code in edit – Miso Piso Feb 05 '19 at 08:51

1 Answers1

7

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
    }
}
Miso Piso
  • 161
  • 9