Created
March 23, 2021 06:41
-
-
Save manuelvicnt/92d1bf42f413d519f0e2cf1aff0f9b9d to your computer and use it in GitHub Desktop.
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
// Implementation of a cold flow backed by a Channel that sends Location updates | |
fun FusedLocationProviderClient.locationFlow() = callbackFlow<Location> { | |
val callback = object : LocationCallback() { | |
override fun onLocationResult(result: LocationResult?) { | |
result ?: return | |
try { offer(result.lastLocation) } catch(e: Exception) {} | |
} | |
} | |
requestLocationUpdates(createLocationRequest(), callback, Looper.getMainLooper()) | |
.addOnFailureListener { e -> | |
close(e) // in case of exception, close the Flow | |
} | |
// clean up when Flow collection ends | |
awaitClose { | |
removeLocationUpdates(callback) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment