简体   繁体   English

如何在 Android 上的协程中使用 LiveData

[英]How to use LiveData in Coroutine on Android

In my application I want use Room database into MVVM architecture and for this I used LiveData with Couroutines .在我的应用程序中,我想在MVVM架构中使用Room数据库,为此我使用LiveDataCouroutines
I write below codes and I want check data, if data is empty then show empty layout.我写下面的代码,我想检查数据,如果数据为,则显示空布局。
I write below codes, but after run application show me Error and application has crashed!我写了下面的代码,但是运行应用程序后显示错误并且应用程序崩溃了!
Dao codes:道码:

@Dao
interface DataDao {

    @Query("SELECT * FROM $my_table ORDER BY id DESC")
    fun getAllData(): LiveData<MutableList<DataEntity>>
}

Repository codes:存储库代码:

class MainRepository @Inject constructor(private val dao: DataDao) {

   fun allData() = dao.getAllData()
}

ViewModel codes:视图模型代码:

@HiltViewModel
class MainViewModel @Inject constructor(private val repository: MainRepository) : ViewModel() {

    val dataList = repository.allData()
    val isEmpty = MutableLiveData<Boolean>()

    fun checkData() = viewModelScope.launch(Dispatchers.Main) {
        if (repository.allData().value!!.isEmpty()) {
            isEmpty.postValue(true)
        } else {
            isEmpty.postValue(false)
        }
    }
}

Show me this error in logcat :logcat中显示此错误:

java.lang.NullPointerException
        at com.myapp.viewmodel.MainViewModel$checkData$1.invokeSuspend(MainViewModel.kt:22)
        at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
        at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
        Suppressed: kotlinx.coroutines.DiagnosticCoroutineContextException: [StandaloneCoroutine{Cancelling}@35a0def, Dispatchers.Main]

Show error for this line: repository.allNotes().value.!.isEmpty()显示此行的错误: repository.allNotes().value.!.isEmpty()

How can I fix it?我该如何解决?

First of all I think you don't need to launch a coroutine in MainViewModel.checkData() method, because there is no suspend functions invoked.首先,我认为您不需要在MainViewModel.checkData()方法中启动协程,因为没有调用suspend函数。 And regarding the error, please check the value in LiveData on null :关于错误,请检查LiveDatanull中的值:

fun checkData() {
    val data = repository.allData().value
    if (data == null || data.isEmpty()) {
        isEmpty.postValue(true)
    } else {
        isEmpty.postValue(false)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM