Skip to content

Instantly share code, notes, and snippets.

@angusholder
Created March 13, 2020 12:32
Show Gist options
  • Save angusholder/5a9e7dd814cc6c728842ebe610bcf364 to your computer and use it in GitHub Desktop.
Save angusholder/5a9e7dd814cc6c728842ebe610bcf364 to your computer and use it in GitHub Desktop.
Controller view lifecycle
package co.mopo.android.ui.base
import android.content.Context
import android.view.View
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import com.bluelinelabs.conductor.Controller
import com.bluelinelabs.conductor.Controller.LifecycleListener
class AndroidXLifecycleListener(
val mainLifecycle: LifecycleRegistry,
val viewLifecycle: LifecycleRegistry
) : LifecycleListener() {
override fun postContextAvailable(controller: Controller, context: Context) {
mainLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_CREATE) // --> State.CREATED;
}
override fun postCreateView(controller: Controller, view: View) {
mainLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_START) // --> State.STARTED;
viewLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_CREATE) // --> State.STARTED;
}
override fun postAttach(controller: Controller, view: View) {
mainLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_RESUME) // --> State.RESUMED;
viewLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_RESUME) // --> State.RESUMED;
}
override fun preDetach(controller: Controller, view: View) {
mainLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE) // --> State.STARTED;
viewLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE) // --> State.STARTED;
}
override fun preDestroyView(controller: Controller, view: View) {
mainLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_STOP) // --> State.CREATED;
viewLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY) // --> State.CREATED;
}
override fun preContextUnavailable(controller: Controller, context: Context) {
// do nothing
}
override fun preDestroy(controller: Controller) {
mainLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY) // --> State.DESTROYED;
}
}
fun <C> makeAndroidXLifecycleListener(controller: C): AndroidXLifecycleListener
where C: Controller, C: LifecycleOwner
{
val mainLifecycle = LifecycleRegistry(controller) // --> State.INITIALIZED
val viewLifecycleOwner = ControllerViewLifecycleOwner()
val viewLifecycle = viewLifecycleOwner.viewLifecycle
val listener = AndroidXLifecycleListener(mainLifecycle, viewLifecycle)
controller.addLifecycleListener(listener)
return listener
}
private class ControllerViewLifecycleOwner : LifecycleOwner {
val viewLifecycle = LifecycleRegistry(this) // --> State.INITIALIZED
override fun getLifecycle() = viewLifecycle
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment