https://kotlinlang.org logo
#compose
Title
# compose
s

Slackbot

07/12/2022, 1:55 PM
This message was deleted.
a

Aaron Waller

07/12/2022, 1:55 PM
in my ViewModel:
Copy code
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:
Copy code
data class Post(
    val id: Int,
    val name: String, 
    val isLiked: Boolean = false,
)
And here my Composable:
Copy code
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.
v

Vahalaru

07/12/2022, 2:17 PM
The problem is in your viewmodel. You need to do a deep copy first then set the isLiked. fun likePost(newPost: Post){ val index = _itemList.indexOf(newPost) _itemList[index] = _itemList[index].copy() _itemList[index].isLiked = true }
3 Views