android - LiveDataScope 发出不调用

标签 android viewmodel android-livedata kotlin-coroutines

我遇到了一个非常不寻常的问题,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/

相关文章:

android - 如何使用 liveData 处理错误

android - 弹出 fragment 后的多个 LiveData 观察者

android - 如何从应用程序的不同部分启动 Activity ?

android - Nexus 7 Linux 内核 : What file to fiddle with for volume control hacking ?

c# - MVC - 列表中的 ICollection 在 POST 时不会返回到 Controller

android - 共享 ViewModel 中的 hasActiveObservers 和 hasObservers false

kotlin - LiveData的正确实现方式

android - 如何为编辑文本添加模糊阴影?

java - 如何将所有文件路径加载到字符串数组中

c# - 在ViewModel中公开属性的正确方法