I'm struggling with some strange problem and hope that anyone can help with some advice.
I have a combination of a Compose View and a ViewModel in my architecture.
Consider following example - I have a collection of Pokemon Cards. I may sell some (remove from the list), buy a new one (add to the list), or borrow some (change status of some element in the list from borrowed = false to true).
data class Card (
val index: Int,
val name: String,
val initialBorrowed: Boolean = false
) {
var isBorrowed: Boolean by mutableStateOf(initialBorrowed)
}
The ViewModel looks like this (simplified):
CardsScreenViewModel( getCardsUseCase, ...) : ViewModel() {
private val _cards: = mutableStateListOf<Card>()
val cards: List<Card> get() = _cards
// some logic code here
fun removeCard(index: Int) {
val cardToRemove = _cards.find { it.index == index }
_cards.remove(cardToRemove)
}
fun markAsBorrowed(index: Int, isBorrowed: Boolean) {
_cards.find{ it.index = index }?.let { card ->
card.isBorrowed = isBorrowed
}
}
}
And the View looks like this (simplified):
@Composable
fun CardsScreen (
viewModel: CardsScreenViewModel,
...
) {
CardsListView(
viewModel.cards,
...
)
}
@Composable
fun CardsListView(
cards: List<Cards>,
...
){
LazyColumn(Modifier...) {
item { Header }
itemsIndexed(
items = cards,
key = {_: Int, item: Card -> item.index}
) {
CardItem(item)
}
}
}
PROBLEM: Everything works fine when you stay on the screen. You can add and remove cards, mark them as borrowed and so on. But when you open another screen (for example Card details) and then go back - the list is in inconsistent or stale state. Some cards are shown as borrowed again, but the last state was that the card not borrowed anymore and so on....
QUESTION: do you have any ideas why the state of the list is stale / broken after going to another screen and then coming back to it?