Skip to content

Custom lifecycle

Valery edited this page Aug 30, 2018 · 5 revisions

If you want to manage the component's lifecycle by yourself, you can do it by using the bindComponentToCustomLifecycle<ComponentClass>(this). Let's see how it works.

Implement the IHasComponent interface, override the createComponent and getComponentKey (if you want) methods, as usual.

class FragmentC : Fragment(), IHasComponent {

    //...code...

    override fun createComponent(): FeatureCComponent = 
        DaggerFeatureCComponent.builder().build()
}

After it you need to get the component itself and its lifecycle. You do it by calling the bindComponentToCustomLifecycle<ComponentClass>(this) method. This method returns a StoredComponent object that contains the component and its lifecycle.

data class StoredComponent<T>(
    val component: T,
    val lifecycle: IComponentLifecycle
)
```kotlin
class FragmentC : Fragment(), IHasComponent {

    //...code...
    private var storedComponent: StoredComponent<FeatureCComponent>? = null

    override fun onResume() {
        super.onResume()
        storedComponent = XInjectionManager.instance.bindComponentToCustomLifecycle<FeatureCComponent>(this)
        storedComponent?.component?.inject(this)
    }
    
    //...code...
}

It is up to you to store the StoredComponent in a variable or not. If you are not going to do it, you could get the StoredComponent by calling the bindComponentToCustomLifecycle<FeatureCComponent>(this) method again, because your component would be stored in the local store until it would not be destroyed.

If it is time to destroy the component, just call the lifecycle.destroy() method of the StoredComponent and the component will be destroyed immediately.

class FragmentC : Fragment(), IHasComponent {

    //...code...

    override fun onPause() {
        super.onPause()
        storedComponent?.lifecycle?.destroy()
        storedComponent = null
    }
   
    //...code...
}

Clone this wiki locally