From d7dbda91c67b30e80e9954498fac6439265fe551 Mon Sep 17 00:00:00 2001 From: Gabriel Souza Date: Tue, 9 Jan 2024 19:03:18 -0300 Subject: [PATCH] fix: event emit on destroy state #280 (#297) * fix: event emit on destroy state #280 * fix lint --- .../androidx/AndroidScreenLifecycleOwner.kt | 23 ++++++++++++------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/voyager-core/src/androidMain/kotlin/cafe/adriel/voyager/androidx/AndroidScreenLifecycleOwner.kt b/voyager-core/src/androidMain/kotlin/cafe/adriel/voyager/androidx/AndroidScreenLifecycleOwner.kt index a24d35b8..e4e5c1b2 100644 --- a/voyager-core/src/androidMain/kotlin/cafe/adriel/voyager/androidx/AndroidScreenLifecycleOwner.kt +++ b/voyager-core/src/androidMain/kotlin/cafe/adriel/voyager/androidx/AndroidScreenLifecycleOwner.kt @@ -92,19 +92,19 @@ public class AndroidScreenLifecycleOwner private constructor() : isCreated = true controller.performRestore(savedState) initEvents.forEach { - lifecycle.handleLifecycleEvent(it) + lifecycle.safeHandleLifecycleEvent(it) } } private fun emitOnStartEvents() { startEvents.forEach { - lifecycle.handleLifecycleEvent(it) + lifecycle.safeHandleLifecycleEvent(it) } } private fun emitOnStopEvents() { stopEvents.forEach { - lifecycle.handleLifecycleEvent(it) + lifecycle.safeHandleLifecycleEvent(it) } } @@ -130,7 +130,7 @@ public class AndroidScreenLifecycleOwner private constructor() : if (activity != null && activity.isChangingConfigurations) return viewModelStore.clear() disposeEvents.forEach { event -> - lifecycle.handleLifecycleEvent(event) + lifecycle.safeHandleLifecycleEvent(event) } } @@ -160,19 +160,19 @@ public class AndroidScreenLifecycleOwner private constructor() : if (lifecycleOwner != null) { val observer = object : DefaultLifecycleObserver { override fun onPause(owner: LifecycleOwner) { - lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE) + lifecycle.safeHandleLifecycleEvent(Lifecycle.Event.ON_PAUSE) } override fun onResume(owner: LifecycleOwner) { - lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_RESUME) + lifecycle.safeHandleLifecycleEvent(Lifecycle.Event.ON_RESUME) } override fun onStart(owner: LifecycleOwner) { - lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_START) + lifecycle.safeHandleLifecycleEvent(Lifecycle.Event.ON_START) } override fun onStop(owner: LifecycleOwner) { - lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_STOP) + lifecycle.safeHandleLifecycleEvent(Lifecycle.Event.ON_STOP) // when the Application goes to background, perform save performSave(outState) @@ -222,6 +222,13 @@ public class AndroidScreenLifecycleOwner private constructor() : else -> null } + private fun LifecycleRegistry.safeHandleLifecycleEvent(event: Lifecycle.Event) { + val currentState = currentState + if (!currentState.isAtLeast(Lifecycle.State.INITIALIZED)) return + + handleLifecycleEvent(event) + } + public companion object { private val initEvents = arrayOf(