Last active
March 16, 2020 06:46
-
-
Save soniccat/9305bc518930956f913f5306ee91ffce to your computer and use it in GitHub Desktop.
Conductor ControllerViewLifecycleOwner
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// To use it add | |
// val viewLifecycleOwner: ControllerViewLifecycleOwner<BaseViewController> | |
// by lazy { ControllerViewLifecycleOwner(this) } | |
// in you BaseViewController | |
class ControllerViewLifecycleOwner<T>(lifecycleController: T) : | |
LifecycleOwner where T : LifecycleOwner, T : Controller { | |
private val controllerRef = WeakReference(lifecycleController) | |
private var lifecycleRegistry: LifecycleRegistry? = null | |
private set | |
override fun getLifecycle(): Lifecycle { | |
createRegistryIfNeeded() | |
return lifecycleRegistry!! | |
} | |
private fun createRegistryIfNeeded() { | |
if (lifecycleRegistry == null) { | |
val controller = controllerRef.get() | |
if (controller != null) { | |
lifecycleRegistry = LifecycleRegistry(controller) | |
} | |
} | |
} | |
init { | |
lifecycleController.addLifecycleListener(object : Controller.LifecycleListener() { | |
override fun postCreateView(controller: Controller, | |
view: View) { | |
createRegistryIfNeeded() | |
lifecycleRegistry?.handleLifecycleEvent(Lifecycle.Event.ON_START) | |
} | |
override fun postAttach(controller: Controller, | |
view: View) { | |
lifecycleRegistry?.handleLifecycleEvent(Lifecycle.Event.ON_RESUME) | |
} | |
override fun preDetach(controller: Controller, | |
view: View) { | |
lifecycleRegistry?.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE) | |
} | |
override fun preDestroyView(controller: Controller, | |
view: View) { | |
lifecycleRegistry?.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY) | |
lifecycleRegistry = null | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment