[英]Use property as accessor for Kotlin Coroutine
Kotlin 協程問題...掙扎着使用屬性而不是 function 作為異步調用的訪問器。
背景是我正在嘗試將FusedLocationProviderClient
與kotlinx-coroutines-play-services
庫一起使用,以便在Task
上使用.await()
方法而不是添加回調......
目前有一個屬性獲取器被踢出以暫停 function,但不確定如何正確啟動協程以避免
找到所需的單位 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()
阻塞直到一個值可用並返回它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.