I found that SharedFlow is collected correctly by collectAsStateWithLifecycle() only when I click a button instead of waiting to timeout or when I change replay to 1. In other cases it is collected only once. StateFlow works correctly. Do you know any explanation of this behavior?
Here are code snippets:
In ViewModel:
private val _question = MutableSharedFlow<Result<Question>>(
replay = 1,
)
val question
get() = _question.asSharedFlow()
private val _questionNumber = MutableStateFlow(0)
val questionNumber
get() = _questionNumber.asStateFlow()
suspend fun nextQuestion() {
val questionWithIndex = questionIterator.next()
_question.emit(Result.success(questionWithIndex.value))
_questionNumber.value = questionWithIndex.index + 1
}
Screen:
val questionResult by questionViewModel.question
.collectAsStateWithLifecycle(initialValue = null)
LaunchedEffect(questionResult) {
givenAnswerViewModel.clearSelectedAnswers()
questionResult?.fold(
onSuccess = {
isLoading = false
question = it
timerViewModel.start()
},
onFailure = {
val messageRes = getHttpFailureMessage(it as? Exception)
snackbarHostState.showSnackbar(context.getString(messageRes))
},
)
}
val sendAnswers: () -> Unit = {
timerViewModel.clear()
givenAnswerViewModel.addAnswer(question)
coroutineScope.launch {
if (questionViewModel.isQuestionLast()) {
givenAnswerViewModel.sendAnswers(
userUUID = userViewModel.userUuid,
token = userViewModel.token,
)
} else {
questionViewModel.nextQuestion()
}
}
}
if (timeLeft == 0L) {
sendAnswers()
}
sendAnswers
is also invoked on clicking a button.
New contributor
ForgotMyUsername is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.