Created
December 9, 2020 11:41
-
-
Save manuelvicnt/558118684eb38af8a27c22f2e5291058 to your computer and use it in GitHub Desktop.
FusedLocationProviderClient.locationFlow
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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