Skip to content

Custom lifecycle

Valery edited this page Aug 8, 2019 · 5 revisions

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

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

class FragmentC : Fragment(), IHasComponent {

    //...code...

    override fun getComponent(): 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<ComponentClass> object that contains the component and its lifecycle.

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

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

    override fun onResume() {
        super.onResume()
        storedComponent = 
            XInjectionManager.instance.bindComponentToCustomLifecycle(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<FeatureCComponent> object by calling the bindComponentToCustomLifecycle<FeatureCComponent>(this) method again. Your component will be stored in the local store until it will not be destroyed.

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

class FragmentC : Fragment(), IHasComponent {

    //...code...

    private var storedComponent: StoredComponent<FeatureCComponent>? = null

    //...code...

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