[FIXED] List does not get updated automatically Compose

Issue

The list does not get updated automatically after adding a new item to the room database, the list only gets updated when the app is restarted. I have used MutableState and Flow but the issue still remains.

CatsRepository:

class CatsRepository @Inject constructor(
    private val catsRemoteDataSource: CatsRemoteDataSource,
    private val favouritesDao: FavouritesDao
) : BaseApiResponse() {

    suspend fun getAllFavourite(): Flow<List<FavouriteEntity>>{
        return flow {
            emit(favouritesDao.getAllFavourite())
        }.flowOn(Dispatchers.IO)
    }
}

CatsViewModel:

@HiltViewModel
class FavouriteViewModel @Inject constructor(private val repository: CatsRepository) :
    ViewModel() {
    init {
        getAllFavourite()
    }

    val response: MutableState<List<FavouriteEntity>> = mutableStateOf(listOf())

    private fun getAllFavourite() {
        viewModelScope.launch {
            repository.getAllFavourite().collect { values ->
                Log.i("tag","item changed")
                response.value = values
            }
        }
    }
}

FavouritesDao:

@Query("SELECT * FROM Favourites")
suspend fun getAllFavourite(): List<FavouriteEntity>

FavouriteScreen:

@Composable
fun FavouriteScreen(favouriteViewModel: FavouriteViewModel,navController: NavController) {
 val favourites = favouriteViewModel.response.value

 FavouriteList(modifier = Modifier, favourites = favourites, navController = navController)
}

Solution

you need to make your dao return live data or flow in order to get updates from it automatically

update your FavouritesDao as follows:

@Query("SELECT * FROM Favourites")
suspend fun getAllFavourite(): Flow<List<FavouriteEntity>>

and update your repository CatsRepository as follows:

class CatsRepository @Inject constructor(
    private val catsRemoteDataSource: CatsRemoteDataSource,
    private val favouritesDao: FavouritesDao
) : BaseApiResponse() {

    suspend fun getAllFavourite(): Flow<List<FavouriteEntity>>{
        return favouritesDao.getAllFavourite();
    }
}

Answered By – Rakshit Tanti

Answer Checked By – Marie Seifert (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published