我遇到了一个非常不寻常的问题,LiveDataScope 没有抛出我的异常,在我的存储库中启动。
问题是,如果代替发射,我放置了一个 livedata 事件,它被分派(dispatch)给观察者,但是使用发射,它不会向它启动事件。
查看型号:
fun launchJob(makeThis: suspend LiveDataScope<ViewState>.() -> Unit): LiveData<ViewState> =
liveData {
viewModelScope.launch {
emitLoad()
try {
makeThis(this@liveData)
} catch (error: Error){
//its work
showErrorEvent.value = Pair(error, true)
// not work
emit(ViewState.Error(error))
}
}
}
viewmodel implementation
/**
* Método responsável por realizar o método de reset de senha.
* */
fun requestReset() = launchJob {
emitSucess(shippingMethodRepository.resetPassword(method))
}
基础存储库
suspend fun getAsyncData(params: P): T {
try {
return api.invoke(params)
} catch (error: Exception) {
error.printStackTrace()
throw error
}
}
正如我所提到的,将发射更改为不同的实时数据, Activity 会观察到它,并且还会读取发射之前的任何代码,以及日志等。
最佳答案
从文档:
The liveData building block serves as a structured concurrency primitive between coroutines and LiveData. The code block starts executing when LiveData becomes active and is automatically canceled after a configurable timeout when the LiveData becomes inactive.
在调用发出函数后未触发观察者的根本原因是因为您的 liveData 已被观察(激活)。
LiveData 构建 block 更适合初始化 liveData 值而不是更改其值。如果您想像这样更改 liveData 值,只需使用 mutableLiveData
关于android - LiveDataScope 发出不调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59987347/