Reputation: 956
I got a ScreenState data class in my ViewModel:
data class ScreenState(
var isLoading: Boolean = true,
val items: List<Posts> = emptyList()
)
and a mutableStateof:
private val _homeScreenState = mutableStateOf(ScreenState())
val homeScreenState: State<ScreenState> = _homeScreenState
Updating the isLoading property works fine, the change gets send to my UI:
_homeScreenState.value = _homeScreenState.value.copy(isLoading = true)
But updating an item inside my List<Posts>
does not work.
Here is how I try to do it:
val updatedList = homeScreenState.value.items.toMutableList()
val index = updatedList.indexOfFirst { it.id == passedPost.id }
updatedList[index] = updatedList[index].copy(isLiked = true)
_homeScreenState.value = _homeScreenState.value.copy(items = updatedList)
I'm trying to update the isLiked Boolean inside my Post data class and show the change in the UI.
I do understand, that this is a normal behaviour and that the mutableStateOf does not update because the ScreenState itself does not update but the item inside the List<Post>
of the ScreenState.
The problem is that I don't know how to trigger the UI to update.
EDIT This is my Post Data Class:
data class Post(
val id: Int,
val name: String,
val description: String,
val isLiked: Boolean = false,
)
Upvotes: 3
Views: 4483
Reputation: 101
data class Post(
val id: Int,
val name: String,
val description: String,
val isLiked: MutableState<Boolean> = mutableStateOf(false),
)
or
class Post(
val id: Int,
val name: String,
val description: String,
isLiked: Boolean = false,
){
val isLiked by mutableStateOf(isLiked)
}
Upvotes: 0