Skip to content

Instantly share code, notes, and snippets.

@manuelvicnt
Created May 3, 2021 12:06
Show Gist options
  • Save manuelvicnt/3adeffc97466f389eeaf89e4b527fe9d to your computer and use it in GitHub Desktop.
Save manuelvicnt/3adeffc97466f389eeaf89e4b527fe9d to your computer and use it in GitHub Desktop.
class LocationDataSource(
private val locationClient: FusedLocationProviderClient
) {
val locationsSource: Flow<Location> = 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