Sky
Sky

Reputation: 197

List does not get updated automatically Compose

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)
}

Upvotes: 1

Views: 189

Answers (1)

Rakshit Tanti
Rakshit Tanti

Reputation: 99

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();
    }
}

Upvotes: 2

Related Questions