How do I create a list where I can track states and still not create a new one each time? (jetpaсk compose)

42 views Asked by At

I'm making an android app, it's going to be a card game.

val players = arrayOf(
    Player(1, "00", 0),
    Player(2, "00", 0),
    Player(3, "00", 0),
    Player(4, "00", 0),
    Player(5, "00", 0),
    Player(6, "00", 0),
    Player(7, "00", 0),
    Player(8, "00", 0),
    Player(9, "00", 0),
    Player(10, "00", 0),
)
val playersState = remember { mutableStateListOf(*players) }

Then I call the display functions:

showPlayers(stateBottomToggle, playersState)
showHandSelection(stateBottomToggle, playersState, value1, value2, value3)

How to create such a list, so that when a change is made in it, the screen is redrawn, without creating the whole list again (as it is resource-intensive).

Ideally, it seems to me, to create a class that will store all common and individual settings, that is, a few switches and this list of players. And pass this instance of the class to each function and work with it. Is it possible to do this and if not, then what can be done?

This is how it works for me at the moment:

players[selectedPlayer-1].hand = key_to_hand_h[hand]
playersState.removeRange(0, 10)
playersState.addAll(players)

That is, I change the original array and then delete the state array and completely recreate it. Of course I find this ineffective and would like to know what can be done?

1

There are 1 answers

7
BenjyTec On

Have a look at the set function of MutableList which is the type that is returned by mutableStateListOf:

abstract operator fun set(index: Int, element: E): E
Replaces the element at the specified position in this list with the specified element.

To update a single element in a list, you can use the following code:

playersState.set(
    selectedPlayer - 1,                                           // index to update
    playersState[selectedPlayer - 1].copy(hand = key_to_hand_h[hand])  // updated Player
)

You can write it even simpler using operator overloading:

playersState[selectedPlayer - 1] = playersState[selectedPlayer - 1].copy(hand = key_to_hand_h[hand])

By using the copy function, you create a new Player instance with the same values and only update the hand value.

Please note that Player should be a data class with immutable properties like this:

data class Player(
    val id: Int,
    val name: String,
    val age: Int
)