无法让我的第一个 Kotlin 协程函数工作
Unable to get my First Kotlin Coroutine Function to Work
我正在努力让我的第一个协程函数工作!我有一个名为 GetContacts 的阻止函数,它可以获取设备联系人。我想用这个查询的结果更新一个 Livedata。这个查询本身运行良好,但我似乎无法让它在 Coroutine 中运行。
这是我的代码
val contactsList: MutableLiveData<List<ContactModel>> = MutableLiveData()
fun getContactList(){
viewModelScope.launch() {
var contacts: List<ContactModel>? = null
withContext(Dispatchers.IO){
contacts = getListOfContactsOnDeviceAsync()
}
contactsList.value = contacts
}
}
private fun getListOfContactsOnDeviceAsync(): List<ContactModel> = GetContactHelper.getContacts()
当我清楚地添加了 Android 协同程序依赖项时,我收到错误 "Module with the Main dispatcher is missing. Add dependency providing the Main dispatcher, e.g. 'kotlinx-coroutines-android'"。
dependencies {
implementation 'com.android.support:multidex:1.0.3'
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2'}
我错过了什么?任何帮助表示赞赏!
我正在努力让我的第一个协程函数工作!我有一个名为 GetContacts 的阻止函数,它可以获取设备联系人。我想用这个查询的结果更新一个 Livedata。这个查询本身运行良好,但我似乎无法让它在 Coroutine 中运行。
这是我的代码
val contactsList: MutableLiveData<List<ContactModel>> = MutableLiveData()
fun getContactList(){
viewModelScope.launch() {
var contacts: List<ContactModel>? = null
withContext(Dispatchers.IO){
contacts = getListOfContactsOnDeviceAsync()
}
contactsList.value = contacts
}
}
private fun getListOfContactsOnDeviceAsync(): List<ContactModel> = GetContactHelper.getContacts()
当我清楚地添加了 Android 协同程序依赖项时,我收到错误 "Module with the Main dispatcher is missing. Add dependency providing the Main dispatcher, e.g. 'kotlinx-coroutines-android'"。
dependencies {
implementation 'com.android.support:multidex:1.0.3'
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2'}
我错过了什么?任何帮助表示赞赏!