0

I have a method that updates local value if I got a spicific json:

override fun onGameStartOpenWord(startOpenWord: StartOpenWord) {
    var word = _state.value.gameState!!.words.find { startOpenWord.word.id == it.id } ?: return
    val tempCopy = word.copy()
    word = word.copy(
            animationStart = startOpenWord.word.times.first().toULong(),
            animationEnd = startOpenWord.word.times.last().toULong()
        )
    val words = _state.value.gameState!!.words.toMutableList()
    val index = words.indexOf(tempCopy)
    logger.debug("Animation should start at ${word.animationStart}, updating word ${tempCopy.id} with index $index")
    words[index] = word
    val gameState = _state.value.gameState?.copy(words = words)
    _state.update { it.copy(gameState = gameState) }
    logger.debug(_state.value.gameState!!.words[index].animationStart)
}

The State created like this:

private val _state = reset() //MutableStateFlow<GameData>
val state = _state.asStateFlow()

Using state like this:

val model = ViewModelsStore.mainFrameViewModel //compose-jb does not have method viewModel<>(), using object to store
val data by model.state.collectAsState()
val stateWord = data.gameState!!.words.find { it.id == word.id }!!

val animationStart = stateWord.animationStart
val animationEnd = stateWord.animationEnd

if (animationStart != null) {
    //do animation stuff
}

Everything else updates correctly (recomposition starts), but the method above does not. However _state does actually update, logs show that clearly. Debbuger showed me that before update() method gameState != _state.value.gameState, but after update() it is.

But recomposition didn't happen and animation didn't start. What is the problem?

AdisAlagic
  • 436
  • 2
  • 8
  • Can you show the code of the state data class? I guess that problem is that you observe the whole state, which is a complex object that holds different inner states. If they are declared as val, that could force compose to skip their updates and therefore not perform recomposition – Steyrix Feb 18 '23 at 18:47
  • `data class GameData(val playerList: PlayerList, val myself: PlayerInfo?, val gameState: GameState?)`. Okay, `GameState` is huge, but everything else work fine. When I update state from something else, it is works perfectly. Even with `val` keyword – AdisAlagic Feb 18 '23 at 19:53

1 Answers1

0

Be careful with listeners. It was my mistake and gameState was overwritten by listener. So recompose didn't happen, because value changed too fast.

AdisAlagic
  • 436
  • 2
  • 8