Daniel
06/09/2021, 7:18 PMensureFineLocation
that handles the whole permission flow and then passing a reference to the function down through the composables.
This seems like it will scale pretty badly though, both in that the activity has a lot of unrelated methods and I've got to pass a lot of free functions.
Also, since registerForActivityResult
is global state I'm not sure the right way to handle repeated calls. I'm currently using a MutableState like so
private val fineLocationStatus = MutableState<Boolean?>(null)
private val requestFineLocationLauncher =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
fineLocationStatus.value = isGranted
}
private fun ensureFineLocation(): Boolean {
val initialCached = fineLocationStatus.value
if (initialCached != null) {
if (!initialCached) showFineLocationMissingError()
return initialCached
}
val permission = Manifest.permission.ACCESS_FINE_LOCATION
if (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) return true
if (shouldShowRequestPermissionRationale(permission)) {
if (!fineLocationRationalePrompt()) {
fineLocationDeniedMsg()
return false
}
}
requestFineLocationLauncher.launch(permission)
val cached = fineLocationStatus.filterNotNull().first()
if (!cached) fineLocationDeniedMsg()
return cached
}
This is a little racy if there are multiple calls before a value is cached. I'm also not sure the value should be cached, so I considered clearing the mutable state before returning. Then I think I'd need to protect ensureFineLocation
with a mutex, though.
I feel like there has to be a better solution. Is there a reason why registerForActivityResult
uses a global callback instead of giving each request a different requestCode so that you can have a suspend fun like launcher.awaitResult
?Ian Lake
06/09/2021, 7:23 PMlaunch
Daniel
06/09/2021, 7:24 PMIan Lake
06/09/2021, 7:25 PMrememberLauncherForActivityResult
works (note: the method was renamed) - it is not a global callback at all, it automatically handles returning the result to specifically the launcher that you call launch
onIan Lake
06/09/2021, 7:25 PMDaniel
06/09/2021, 7:26 PMIan Lake
06/09/2021, 7:27 PMDaniel
06/09/2021, 7:27 PMremember
doesn't persist through config changes/process deathIan Lake
06/09/2021, 7:28 PMrememberSaveable
for the unique keyDaniel
06/09/2021, 7:28 PMDaniel
06/09/2021, 7:29 PMremember
, not rememberSaveable
. If I use this do I have to refactor everything to use rememberSaveable
?Ian Lake
06/09/2021, 7:31 PMDaniel
06/09/2021, 7:31 PMIan Lake
06/09/2021, 7:32 PMactivity-compose
APIs in https://issuetracker.google.com/190615266 if you'd like to star that and get notified on when those docs become availableManuel Vivo
06/10/2021, 7:14 AM