Reputation: 1314
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?
Upvotes: 2
Views: 157
Reputation: 5371
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()
}
}
Upvotes: 1