I am having a lazy vertical grid which is rendered with a mutable list of items. i want alter the items properties in clicking in it. Classes used: Screen State
@Keep
data class ScreenState(
val isLoading: Boolean = false,
var items: MutableList<Item> = mutableListOf(),
val error: String? = null,
val endReached: Boolean = false,
val page: Int = 0,
val isInitialLoad : Boolean= true,
val isEmpty:Boolean = false,
val isFilterApplied:Boolean = false
)
List item data class:
@Keep
data class Item(
val id:Int,
var isLIked: Boolean = false,
var name: String? = "",
var desig: String = ",
var imageUrl: String = "",
)
Inside viewModel: create a variable to store the state
var state by mutableStateOf(ScreenState())
On Api response success i am adding the items from json to the list of state object.
state = state.copy(
items = ((state.items + itemsFromResposne) as MutableList<AllDoctorsResponse.Data.Doctor>),
page = newKey,
endReached = items.isEmpty(),
isEmpty = (state.page == 0 && items.isEmpty() )
)
And adding this state.items in a lazy vertical grid
LazyVerticalGrid( //doctors list grid
state = rememberLazyGridState(),
cells = GridCells.Fixed(2),
modifier = Modifier.zIndex(2f)
.padding(top = 20.dp)
.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(10.dp),
horizontalArrangement = Arrangement.spacedBy(17.dp),
content = {
itemsIndexed(screenState.items) { index, item
ListItemComposable(index,item,onclick-{
// Need the code to update item.liked = true from view model
})
}
}
When the item is clicked i want to change the properties inside the list item object. But tits not rflecting in the screen on real time, but when its scrolled it gets recomposed and it gets reflected. How make it reflect and persist the state even when scrolled on and off . Should i use a snapshot or please help how to do it. This is code i used in viewmodel to update the item object
viewModelScope.launch {
val alteredList = state.items.also {
it.forEach {
if (it.id == item.id)
it.liked = false
}
}
}
//add new list as all doctors list
state = state.copy(
items = alteredList
)