-
-
Save hichamboushaba/39e64ecaac1fb223a15d14ca807ee7ea to your computer and use it in GitHub Desktop.
This file contains 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 PermissionManager( | |
private val context: Context, | |
private val activityProvider: ActivityProvider | |
) { | |
... | |
suspend fun requestPermissions(vararg permissions: String): Map<String, PermissionStatus> { | |
val key = "permission_${keyIncrement.getAndIncrement()}" | |
var isLaunched = false | |
return activityProvider.activityFlow | |
.mapLatest { currentActivity -> | |
var launcher: ActivityResultLauncher<Array<out String>>? = null | |
try { | |
suspendCancellableCoroutine<Map<String, PermissionStatus>> { continuation -> | |
launcher = currentActivity.activityResultRegistry.register( | |
key, | |
ActivityResultContracts.RequestMultiplePermissions() | |
) { result -> | |
continuation.resume(permissions.associateWith { | |
if (result[it] == true) { | |
PermissionGranted | |
} else { | |
val shouldShowRationale = | |
currentActivity.shouldShowRequestPermissionRationale(it) | |
PermissionDenied(shouldShowRationale) | |
} | |
}) | |
} | |
if (!isLaunched) { | |
launcher!!.launch(permissions) | |
isLaunched = true | |
} | |
} | |
} finally { | |
launcher?.unregister() | |
} | |
} | |
.first() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment