Kotlin 协程问题...使用属性而不是函数作为异步调用的访问器而苦苦挣扎。
背景是我正在尝试将FusedLocationProviderClient
与kotlinx-coroutines-play-services
库一起使用,以便在Task
上使用.await()
方法,而不是添加回调......
当前有一个属性 getter 踢出到挂起函数,但不确定如何正确启动协程以避免
所需单位找到 XYZ
错误。。。
val lastUserLatLng: LatLng?
get() {
val location = lastUserLocation
return if (location != null) {
LatLng(location.latitude, location.longitude)
} else {
null
}
}
val lastUserLocation: Location?
get() {
GlobalScope.launch {
return@launch getLastUserLocationAsync() <--- ERROR HERE
}
}
private suspend fun getLastUserLocationAsync() : Location? = withContext(Dispatchers.Main) {
return@withContext if (enabled) fusedLocationClient.lastLocation.await() else null
}
关于如何处理这个问题的任何想法?
属性不能是异步的。通常,不应同步异步调用。当您需要值时,您必须返回一个Deferred
并对其调用await()
。
val lastUserLatLng: Deferredd<LatLng?>
get() = GlobalScope.async {
lastUserLocation.await()?.run {
LatLng(latitude, longitude)
}
}
val lastUserLocation: Deferred<Location?>
get() = GlobalScope.async {
getLastUserLocationAsync()
}
private suspend fun getLastUserLocationAsync() : Location? = withContext(Dispatchers.Main) {
return@withContext if (enabled) fusedLocationClient.lastLocation.await() else null
}
但从技术上讲,这是可能的,尽管你不应该这样做。runBlocking()
块,直到值可用并返回它。