Skip to content

Instantly share code, notes, and snippets.

@manuelvicnt
Created December 9, 2020 11:34
Show Gist options
  • Save manuelvicnt/769eb3ab3e66ea75794fc65df284a60c to your computer and use it in GitHub Desktop.
Save manuelvicnt/769eb3ab3e66ea75794fc65df284a60c to your computer and use it in GitHub Desktop.
FusedLocationProviderClient.awaitLastLocation() code
// Extension function on FusedLocationProviderClient, returns last known location
suspend fun FusedLocationProviderClient.awaitLastLocation(): Location =
// Create a new coroutine that can be cancelled
suspendCancellableCoroutine<Location> { continuation ->
// Add listeners that will resume the execution of this coroutine
lastLocation.addOnSuccessListener { location ->
// Resume coroutine and return location
continuation.resume(location)
}.addOnFailureListener { e ->
// Resume the coroutine by throwing an exception
continuation.resumeWithException(e)
}
// End of the suspendCancellableCoroutine block. This suspends the
// coroutine until one of the callbacks calls the continuation parameter.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment