Skip to content

Instantly share code, notes, and snippets.

@manuelvicnt
Created December 9, 2020 11:41
Show Gist options
  • Save manuelvicnt/558118684eb38af8a27c22f2e5291058 to your computer and use it in GitHub Desktop.
Save manuelvicnt/558118684eb38af8a27c22f2e5291058 to your computer and use it in GitHub Desktop.
FusedLocationProviderClient.locationFlow
// Send location updates to the consumer
fun FusedLocationProviderClient.locationFlow() = callbackFlow<Location> {
// A new Flow is created. This code executes in a coroutine!
// 1. Create callback and add elements into the flow
val callback = object : LocationCallback() {
override fun onLocationResult(result: LocationResult?) {
result ?: return // Ignore null responses
for (location in result.locations) {
try {
offer(location) // Send location to the flow
} catch (t: Throwable) {
// Location couldn't be sent to the flow
}
}
}
}
// 2. Register the callback to get location updates by calling requestLocationUpdates
requestLocationUpdates(
createLocationRequest(),
callback,
Looper.getMainLooper()
).addOnFailureListener { e ->
close(e) // in case of error, close the Flow
}
// 3. Wait for the consumer to cancel the coroutine and unregister
// the callback. This suspends the coroutine until the Flow is closed.
awaitClose {
// Clean up code goes here
removeLocationUpdates(callback)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment