Android Kotlin Task To Be Executed Using Coroutines
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 somet
Solution 1:
The kotlinx-coroutines-play-services
library has a Task<T>.await(): T
helper.
import kotlinx.coroutines.tasks.await
suspendfungetLocation(): Location? =
LocationServices.getFusedLocationProviderClient(context).lastLocation.await()
Alternatively take a look at Blocking Tasks
It would be used the next way:
suspendfungetLocation(): Location? =
withContext(Dispachers.IO){
val flpc = LocationServices.getFusedLocationProviderClient(context)
try{
return@withContext Tasks.await(flpc.lastLocation)
catch(ex: Exception){
ex.printStackTrace()
}
return@withContextnull
}
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)
...
}
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.
Solution 2:
Another way that I have don this that can also be used with any callback type interface is to use suspendCoroutine<T> {}
.
So for this example it would be:
suspendfungetLocation(): Location? {
return suspendCoroutine<Location?> { continuation ->
val flpc = LocationServices.getFusedLocationProviderClient(it)
flpc.lastLocation.addOnSuccessListener { location ->
continuation.resume(location)
}
// you should add error listener and call 'continuation.resume(null)'// or 'continuation.resumeWith(Result.failure(exception))'
}
}
Post a Comment for "Android Kotlin Task To Be Executed Using Coroutines"