需要权限的生命周期感知组件
Lifecycle Aware Component that needs Permission
假设我有一个组件需要根据 activity 的生命周期进行初始化和销毁。但是,此组件需要先获得用户的许可。最好的方法是什么?
我是否必须在两个不同的位置订阅同一个观察者,或者有没有代码重复的更好方法?
您可以实现生命周期感知class 封装权限敏感工作:
class MyLifecycleAware {
private var blObject: Any? = null
/**
* Manually call this method when permission granted
*/
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun init() = withPermission {
// code will be invoked only if permission was granted
blObject = TODO("Initialize business logic")
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun destroy() {
blObject?.destroy()
blObject = null
}
/**
* Wrap any permission sensitive actions with this check
*/
private inline fun withPermission(action: () -> Unit) {
val permissionGranted = TODO("Check permission granted")
if (permissionGranted)
action()
}
}
假设我有一个组件需要根据 activity 的生命周期进行初始化和销毁。但是,此组件需要先获得用户的许可。最好的方法是什么?
我是否必须在两个不同的位置订阅同一个观察者,或者有没有代码重复的更好方法?
您可以实现生命周期感知class 封装权限敏感工作:
class MyLifecycleAware {
private var blObject: Any? = null
/**
* Manually call this method when permission granted
*/
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun init() = withPermission {
// code will be invoked only if permission was granted
blObject = TODO("Initialize business logic")
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun destroy() {
blObject?.destroy()
blObject = null
}
/**
* Wrap any permission sensitive actions with this check
*/
private inline fun withPermission(action: () -> Unit) {
val permissionGranted = TODO("Check permission granted")
if (permissionGranted)
action()
}
}