So I have a quiz app, I have a function in the viewmodel to submit an answer and update the current score if it is correct. However, when this function is called in the ui, for some reason it doesn’t contain the updated state, instead it only updates after it is called the second time.
UI:
AnswerContainer(
answer = if (state.askedQuestions.size != state.questionSize) state.answersId.shuffled() else state.answersId
) { answer ->
submitAnswer(sectionIndex, answer)
if (state.askedQuestions.size == state.questionSize) {
Log.d("Score-Inside-AnswerLambda", "Your current score is: ${state.currentScore}")
navigateToResult(
state.questionSize,
state.correctItems,
state.currentScore
)
} else {
Log.d("Score-Inside-AnswerLambda", "Your current score is: ${currentScore}, items correct is ${state.correctItems}")
}
}
Viewmodel:
fun submitAnswer(sectionIndex: Int, answer: String) {
val isCorrect = _state.value.currentQuestion.answer == answer
Log.d("Result", if (isCorrect) "it is correct" else "it is wrong")
_state.update { currentState ->
val updatedScore = if (isCorrect) currentState.currentScore + 200 else currentState.currentScore
val updatedCorrectItems = if (isCorrect) currentState.correctItems + 1 else currentState.correctItems
currentState.copy(
currentScore = updatedScore,
correctItems = updatedCorrectItems
)
}
Log.d("Score-From-ViewModel", "Current score: ${state.value.currentScore}, Correct items: ${_state.value.correctItems}")
selectNewQuestion(sectionIndex)
}
The state is updated correctly in the viewmodel, but in the ui it isn’t.
enter image description here