Search code examples
androidkotlinandroid-roomdaoandroid-viewmodel

Get single item from Room DB. Call the function from view model


So my general question is how to call a function from view model for @Query where you have to pass something and then return something. My simple example:

DAO

@Query ("SELECT * FROM table_name WHERE id = :id LIMIT 1")
fun getItemById (id: Long) : MyItem

Repo

fun getItemById (id: Long) : MyItem {
return itemDao.getItemById(id)
}

I know that it cannot and should not be done on ui thread. For inserting and deleting an item i use viewModelScope job but i cannot (maybe just don`t know how to) use it to return anything. If i return it everywhere as LiveData, then it works just like that:

ViewModel

fun itemById(id: Long): LiveData<MyItem> {
 return itemRepo.getItemById(id)
}

And then i observe it in a Fragment/Activity:

viewModel.itemById(id).observe(this, Observer {
 // using it
})

The thing is, that i dont really need it to be an observable livedata. I only need to get it once, check condition and thats it. So maybe someone could recommend how to do it, without it being a livedata. Or should i leave it a live data?


Solution

  • If you want to get the update only once, then I recommend SingleLiveEvent instead of LiveData. Here is the class provided by google: Github link

    A blog on how to use it: Link

    The only drawback of SingleLiveEvent is that it can't have multiple observers.

    If you don't like LiveData, you could try RxJava's Single [Observable]