I have this code in which I am trying to observe a variable from my viewmodel. However, whenever I observe the variable, it always returns false, which is the default value, even though it should be returning true. I don't understand why it's not working, any idea and advice would be great.
This is the viewmodel part:
val isSuccessful = MutableLiveData(false)
fun acceptAgreement() = currentAgreement.value?.let {
viewModelScope.launch {
runCatching { agreementsRepository.acceptAgreement(it.id) }
.onSuccess { isSuccessful.postValue(true) }
.onFailure { isSuccessful.postValue(false) }
}
}
The observation in the fragment, where it always returns the showError():
binding.btnAccept.setOnClickListener { onAccept().also { continue()} }
private fun onAccept() = viewModel.acceptAgreement()
private fun continue() {
viewModel.isSuccessful.observe(viewLifecycleOwner, {
if (it) { start() } else { showError() }
})
}
Repository:
suspend fun acceptAgreement(id: String) = changeAgreement(id, status.ACCEPTED)
private suspend fun changeAgreement(id: String, status: status) {
try { agreementsService.changeAgreement(id, status.serialize()) }
catch (e: Throwable) { logger.error(this::class.java.name, "Failed to change status ${id}", e) }
}