[英]Lifecycle Aware Component that needs Permission
Let's say I have a component that needs to be initialized and destroyed depending on the lifecycle of the activity.假设我有一个组件需要根据活动的生命周期进行初始化和销毁。 However, this component needs to be granted permissions from the user first.
但是,该组件需要先获得用户的权限。 What is the best way to do that?
最好的方法是什么?
Do I have to subscribe to the same observer in two different positions or there is a better way to do it without code duplication?我是否必须在两个不同的位置订阅同一个观察者,或者有没有代码重复的更好方法?
You can implement life cycle aware class encapsulates permission sensitive work:您可以实现生命周期感知类封装权限敏感的工作:
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()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.