英文:
MutableStateFlow does not recomposes value
问题
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)
}
英文:
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?
答案1
得分: 0
小心处理监听器。这是我的错误,gameState
被监听器覆盖了。因此,重新组合没有发生,因为值变化得太快。
英文:
Be careful with listeners. It was my mistake and gameState
was overwritten by listener. So recompose didn't happen, because value changed too fast.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论