Skip to content

Instantly share code, notes, and snippets.

@manuelvicnt
Created March 23, 2021 06:41
Show Gist options
  • Save manuelvicnt/92d1bf42f413d519f0e2cf1aff0f9b9d to your computer and use it in GitHub Desktop.
Save manuelvicnt/92d1bf42f413d519f0e2cf1aff0f9b9d to your computer and use it in GitHub Desktop.
// 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