假设我有一个需要根据活动的生命周期初始化和销毁​​的组件。但是,首先需要从用户授予此组件权限。最好的方法是什么?

我是否必须在两个不同的位置订阅相同的观察者,或者有更好的方法来做到没有代码重复?

最佳答案

您可以实现生命周期感知类,封装对权限敏感的工作:

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()
    }
}

09-30 23:21