Skip to content

Instantly share code, notes, and snippets.

@0xBADDCAFE
Last active May 14, 2019 02:54
Show Gist options
  • Save 0xBADDCAFE/f1a7ea18815046b759886acda7b879e6 to your computer and use it in GitHub Desktop.
Save 0xBADDCAFE/f1a7ea18815046b759886acda7b879e6 to your computer and use it in GitHub Desktop.
import android.content.pm.PackageManager
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
val runWithCheck: MutableMap<Int, (Boolean) -> Unit> = mutableMapOf()
suspend fun Fragment.withCheck(vararg requests: String, run: (() -> Unit)? = null) = suspendCoroutine<Boolean> { cont ->
val isGranted = requests.map {
ContextCompat.checkSelfPermission(activity!!, it) == PackageManager.PERMISSION_GRANTED
}.fold(true, { acc, b -> acc && b })
if (isGranted) {
run?.invoke()
cont.resume(true)
} else {
val requestCode = requests.hashCode() and 0xffff
requestPermissions(requests, requestCode)
runWithCheck[requestCode] = { granted ->
if (granted) run?.invoke()
cont.resume(granted)
}
}
}
fun Fragment.onRequestPermissionsResultForSuspend(requestCode: Int, grantResults: IntArray) {
val allGranted = grantResults.fold(true, { acc, i ->
acc && i == PackageManager.PERMISSION_GRANTED
})
runWithCheck[requestCode]?.invoke(allGranted)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment