Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Android Permissions with RxJava
import rx.Observable
interface RxPermission {
val isGranted: Boolean
fun request(): Observable<Boolean>
}
import android.Manifest
import android.app.Activity
import android.content.pm.PackageManager
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import rx.Observable
import rx.subjects.PublishSubject
class RxPermissions(private val activity: Activity) {
private val register = mutableMapOf<Int, CompatRxPermission>()
private var lastRequestCode = 0
fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
register[requestCode]?.apply {
if (permissions.isNotEmpty()) {
onResult(permissions, grantResults)
}
}
}
fun of(vararg permissions: String): RxPermission {
val requestCode = ++lastRequestCode
val permission = CompatRxPermission(activity, permissions, requestCode)
register[requestCode] = permission
return permission
}
fun ofExternalStorage() = of(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
fun ofAccessLocation() = of(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
private class CompatRxPermission(private val activity: Activity,
private val permissions: Array<out String>,
private val requestCode: Int) : RxPermission {
private lateinit var request: PublishSubject<Boolean>
override val isGranted: Boolean = permissions.all {
ContextCompat.checkSelfPermission(activity, it) == PackageManager.PERMISSION_GRANTED
}
override fun request(): Observable<Boolean> = if (isGranted) {
Observable.just(true)
} else {
ActivityCompat.requestPermissions(activity, permissions, requestCode)
PublishSubject.create<Boolean>().apply { request = this }
}
fun onResult(permissions: Array<String>, grantResults: IntArray) {
request.onNext(this.permissions.all { permissions.contains(it) }
&& grantResults.all { it == PackageManager.PERMISSION_GRANTED })
request.onCompleted()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment