Aaron Waller
10/16/2022, 9:16 AMFlow<List<Favorite>>
and I collect it in my ViewModel.
Whenever the user adds a Favorite I execute this function in my VM:
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?Aaron Waller
10/16/2022, 9:39 AMfun 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 itagrosner
10/16/2022, 11:04 AMAaron Waller
10/16/2022, 3:35 PMRadoslaw Juszczyk
10/17/2022, 5:11 AMAaron Waller
10/17/2022, 5:25 AM