比方说,我有一个组件需要根据活动的生命周期进行初始化和销毁。但是,需要首先从用户授予此组件权限。最好的方法是什么?
我是否必须在两个不同的位置订阅相同的观察者,或者有更好的方法来做到没有代码重复?
答案 0 :(得分:0)
您可以实现生命周期感知类,封装对权限敏感的工作:
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()
}
}