Created
May 3, 2021 12:06
-
-
Save manuelvicnt/3adeffc97466f389eeaf89e4b527fe9d 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
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