Last active
May 14, 2019 02:54
-
-
Save 0xBADDCAFE/f1a7ea18815046b759886acda7b879e6 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
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