我有這段代碼,我試圖從我的視圖模型中觀察一個變數。但是,每當我觀察變數時,它總是回傳 false,這是默認值,即使它應該回傳 true。我不明白為什么它不起作用,任何想法和建議都會很棒。
這是視圖模型部分:
val isSuccessful = MutableLiveData(false)
fun acceptAgreement() = currentAgreement.value?.let {
viewModelScope.launch {
runCatching { agreementsRepository.acceptAgreement(it.id) }
.onSuccess { isSuccessful.postValue(true) }
.onFailure { isSuccessful.postValue(false) }
}
}
片段中的觀察,它總是回傳 showError():
binding.btnAccept.setOnClickListener { onAccept().also { continue()} }
private fun onAccept() = viewModel.acceptAgreement()
private fun continue() {
viewModel.isSuccessful.observe(viewLifecycleOwner, {
if (it) { start() } else { showError() }
})
}
存盤庫:
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) }
}
uj5u.com熱心網友回復:
isSuccessful.postValue(
runCatching { agreementsRepository() }.isSuccess
)
uj5u.com熱心網友回復:
而不是使用isSuccessful.postValue()use isSuccessful.value = true。我發現該分配而不是postValue方法更新了 LiveData 的注冊觀察者。
uj5u.com熱心網友回復:
在運行 onAccept 之后運行 continue() 是否有原因?
我相信正在發生的事情是你在觀察之前沒有設定觀察者。
所以你的流程是:
onAccept -> 觸發 livedata 的更新。繼續 -> 設定 livedata 的觀察者。
我建議您將方法呼叫“continue()”移動到片段的 onCreateView 方法中。無論如何,它不會被觸發,直到它改變視圖模型中的狀態。
您還需要檢查是否設定了片段的 viewLifecycleOwner。
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val binding = FragmentYourFragmentNameBinding.inflate(inflater, container, false).apply {
lifecycleOwner = viewLifecycleOwner
}
continue()
return binding.root
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/431236.html
上一篇:android片段中的線性布局
