I want to notify the user when the item already ex...
# android
a
I want to notify the user when the item already exists in the room database. The list is a Flow
Flow<List<Favorite>>
and I collect it in my ViewModel. Whenever the user adds a Favorite I execute this function in my VM:
Copy code
fun addToFavorite(favorite: Favorite, alreadyFavorite: () -> Unit, addedToFavorite: () -> Unit) {
    viewModelScope.launch {

        favoriteRepository.getFavorites().collect(){ favoriteList -> 
            if(favoriteList.contains(favorite)){
                alreadyFavorite()
            }else{
                addedToFavorite() 
                favoriteRepository.insertFavorite(favorite)
            }
        } 
    }
}
Now the problem here is that favoriteRepostitory.insertFavorite() adds the item to the room database and triggers the getFavorites().collect. So an endless loop gets created and the item is added to the room database indefinitely. How can I get the result of my getFavorites Flow without using collect? Or is there any other way?
Flow.first() was what I was looking for! Changing it to:
Copy code
fun addToFavorite(
    favorite: Favorite,
    alreadyFavorite: () -> Unit,
    addedToFavorite: () -> Unit
) {
    viewModelScope.launch {

        val favoriteList = favoriteRepository.getFavorites().first()
        if (favoriteList.contains(favorite)) {
            alreadyFavorite()
        } else {
            addedToFavorite()
            favoriteRepository.insertFavorite(favorite)
        }
    }
}
solved it
a
Why load the entire list to just check if it exists in db? You can just do an exists on a select by id of your favorite
👍🏼 1
👍 1
a
You are absolutely right, thank you
r
@Aaron Waller most likely you should not be wrapping kotlin's coroutines Flow into a function with callbacks. One of the main reasons behind kotlin coroutines was to avoid so called 'callback hell'. I think you should reconsider how is your code which calls that function written. For example you could create a suspending function which returns a Boolean (true-added, false-already there).
1
a
@Radoslaw Juszczyk yes I did that and its working perfect. Thank you
125 Views