Last active
September 1, 2021 06:50
-
-
Save LouisCAD/abad7446acd013e457d148d729689049 to your computer and use it in GitHub Desktop.
Exposes Location updates from Android's LocationManager as a Flow. Also see https://gist.github.com/LouisCAD/0a648e2b49942acd2acbb693adfaa03a
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
import android.location.Criteria | |
import android.location.Location | |
import android.location.LocationListener | |
import android.Manifest | |
import android.os.Bundle | |
import androidx.annotation.RequiresApi | |
import kotlinx.coroutines.* | |
import kotlinx.coroutines.flow.Flow | |
import kotlinx.coroutines.flow.callbackFlow | |
import splitties.systemservices.locationManager // See https://splitties.louiscad.com/modules/systemservices/ | |
@RequiresApi(anyOf = [Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION]) | |
fun androidLocationFlow( | |
providerCriteria: Criteria, | |
minTime: Long, | |
minDistance: Float | |
): Flow<Location> = callbackFlow { | |
val provider = locationManager.getBestProvider(providerCriteria, true /* enabled only */) | |
val listener = object : LocationListener { | |
override fun onLocationChanged(location: Location) { | |
trySend(location) | |
} | |
override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) = Unit | |
override fun onProviderEnabled(provider: String?) = Unit | |
override fun onProviderDisabled(provider: String?) = Unit | |
} | |
locationManager.requestLocationUpdates(provider, minTime, minDistance, listener) | |
launch { | |
val lastKnownLocation = Dispatchers.IO { | |
locationManager.getLastKnownLocation(provider) | |
} | |
trySend(lastKnownLocation) | |
} | |
awaitClose { | |
locationManager.removeUpdates(listener) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment