Last active
August 8, 2016 04:05
-
-
Save eungju/3be7da954ebc8ed96a4d27acb4b065bc to your computer and use it in GitHub Desktop.
Android Permissions with RxJava
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
import rx.Observable | |
interface RxPermission { | |
val isGranted: Boolean | |
fun request(): Observable<Boolean> | |
} |
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
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