Home > Mobile >  mutableStateListOf change not reflecting in UI - Jetpack Compose
mutableStateListOf change not reflecting in UI - Jetpack Compose

Time:07-13

in my ViewModel:

private val _itemList = mutableStateListOf<Post>()
val itemList: List<Post> = _itemList

fun likePost(newPost: Post){
        val index = _itemList.indexOf(newPost)
        _itemList[index] = _itemList[index].copy(isLiked = true)
}

Here my Post data class:

data class Post(
    val id: Int,
    val name: String, 
    val isLiked: Boolean = false,
)

And here my Composable:

val postList = viewModel.itemList

LazyRow(content = {

    items(postList.size) { i ->
        val postItem = postList[i]
        PostItem(
            name = postItem.name,
            isLiked = postItem.isLiked,
            likePost = { viewModel.likePost(postItem)}
        )

    }
}) 

The change does not update in the UI instantly, I first have to scroll the updated item out of the screen so it recomposes or switch to another Screen and go back to see the change.

CodePudding user response:

You are returning a List<> effectively and not MutableStateList from your ViewModel.

If you want the list to not be mutable from the view, I happen to use MutableStateFlow<List<>> and return StateFlow<List<>>. You could also just convert it to a list in your composable.

CodePudding user response:

For some reason it doesn't like updating, it will add and delete and update instantly. You have to do it this way when updating for our to update the state.

fun likePost(newPost: Post){
     val index = _itemList.indexOf(newPost)
     _itemList[index] = _itemList[index].copy()
    _itemList[index].isLiked = true

}

  • Related