我正在看书学习android。根据这本书,我需要创建一个存储库,从网络响应中获取数据。我还创建了一个livedata来存储信息。这是我书上的代码。
object Repository {
fun searchPlaces(query: String) = liveData(Dispatchers.IO) {
val result = try {
val placeResponse = SunnyWeatherNetwork.searchPlaces(query)
if (placeResponse.status == "ok") {
val places = placeResponse.places
Result.success(places)
} else {
Result.failure(RuntimeException("response status is ${placeResponse.status}"))
}
} catch (e: Exception) {
Result.failure<Place>(e)
}
emit(result)
}
但是当我复制代码时,我发现第二行的Dispatchers。IO是错误的。我试图导入kotlinx.coroutines.Dispatchers, IDE找不到它。最后,我放弃了代码,应用程序成功运行。我不能理解具体的原理
这是我的build.gradle。
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9"
和如何使用Dispatchers.IO?
Dispatchers.IO
属于kotlinx-coroutines-core
包。
添加kotlinx-coroutines-core
实现模块的build.gradle
dependencies{
def coroutinesVersion = '1.5.2-native-mt'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutinesVersion"
}