问题描述
作为示例,我使用FusedLocationProviderClient访问当前位置,它返回一个任务,回调将最终返回该位置.该方法如下所示:
As an example, I'm using FusedLocationProviderClient to access the current location, which returns a task which callback will eventually return the location. The method looks something like follows:
fun getLocation(callback: MyCallback){
val flpc = LocationServices.getFusedLocationProviderClient(it)
flpc.lastLocation.addOnSuccessListener {
callback.onLocation(it)
}
}
是否可以对此进行转换,以便可以使用例程来挂起此函数并等待flpc.lastLocation
返回的任务,以便可以在此方法中将其返回,从而摆脱该回调?例如这样的东西:
Is it possible to transform this so that I can use corroutines to suspend this function and wait for the task returned by flpc.lastLocation
so I can return it in this method and this way get rid of that callback? For example something like this:
suspend fun getLocation(): Location? =
withContext(Dispachers.IO){
val flpc = LocationServices.getFusedLocationProviderClient(it)
return@withContext flpc.lastLocation.result()
}
我的问题是,协程周围是否有东西可以返回Task
的结果(在本例中为Task<Location>
)
My question is if there is something around coroutines where I can return the result of a Task
(in this example, a Task<Location>
)
提前谢谢!
推荐答案
kotlinx-coroutines-play-services
库具有 Task<T>.await(): T
助手.
import kotlinx.coroutines.tasks.await
suspend fun getLocation(): Location? =
LocationServices.getFusedLocationProviderClient(context).lastLocation.await()
或者查看阻止任务
它将以另一种方式使用:
It would be used the next way:
suspend fun getLocation(): Location? =
withContext(Dispachers.IO){
val flpc = LocationServices.getFusedLocationProviderClient(context)
try{
return@withContext Tasks.await(flpc.lastLocation)
catch(ex: Exception){
ex.printStackTrace()
}
return@withContext null
}
仅出于示例目的而添加到此示例中,将以以下方式完成对getLocation()
的调用:
Just to add to this example, for completion purposes, the call to getLocation()
would be done the next way:
coroutineScope.launch(Dispatchers.Main) {
val location = LocationReceiver.getLocation(context)
...
}
但是,这通过不利用可用的回调并阻塞IO调度程序上的线程而否定了协程的好处,如果有替代方法,则不应使用.
However this negates the benefits of coroutines by not leveraging the available callback and blocking a thread on the IO dispatcher and should not be used if the alternative is available.
这篇关于使用协同程序执行Android Kotlin任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!