From 19a553880060fb9074ee10c4bff87e2630d590b4 Mon Sep 17 00:00:00 2001 From: Isaac Udy Date: Sun, 28 Apr 2024 16:36:17 +1200 Subject: [PATCH] Fix issue with restoring dynamic containers and retaining active container state --- .../container/ComposableNavigationContainer.kt | 18 ++++++++++++++---- .../dev/enro/core/NavigationContainerTests.kt | 1 + 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/enro-core/src/main/java/dev/enro/destination/compose/container/ComposableNavigationContainer.kt b/enro-core/src/main/java/dev/enro/destination/compose/container/ComposableNavigationContainer.kt index 9898393d..682aab8f 100644 --- a/enro-core/src/main/java/dev/enro/destination/compose/container/ComposableNavigationContainer.kt +++ b/enro-core/src/main/java/dev/enro/destination/compose/container/ComposableNavigationContainer.kt @@ -299,10 +299,20 @@ public class ComposableNavigationContainer internal constructor( mutableStateOf(Unit) }, stateSaver = object : Saver { - override fun restore(value: Bundle) = when(registrationStrategy) { - ContainerRegistrationStrategy.DisposeWithComposition -> this@ComposableNavigationContainer.restore(value) - ContainerRegistrationStrategy.DisposeWithCompositionDoNotSave -> Unit - ContainerRegistrationStrategy.DisposeWithLifecycle -> Unit + override fun restore(value: Bundle) { + // When restoring, there are some cases where the active container is not the container that is being restored, + // and performing the restore might set that container to be active when that's not actually what we want, + // so we're going to remember the currently active container key, before performing the restore, + // and then re-set the active container afterwards. + val activeBeforeRestore = context.containerManager.activeContainer?.key + when (registrationStrategy) { + ContainerRegistrationStrategy.DisposeWithComposition -> this@ComposableNavigationContainer.restore(value) + ContainerRegistrationStrategy.DisposeWithCompositionDoNotSave -> Unit + ContainerRegistrationStrategy.DisposeWithLifecycle -> Unit + } + if (activeBeforeRestore != null) { + context.containerManager.setActiveContainerByKey(activeBeforeRestore) + } } override fun SaverScope.save(value: Unit): Bundle? = when(registrationStrategy) { diff --git a/enro/src/androidTest/java/dev/enro/core/NavigationContainerTests.kt b/enro/src/androidTest/java/dev/enro/core/NavigationContainerTests.kt index 309b2e4b..6c00bf25 100644 --- a/enro/src/androidTest/java/dev/enro/core/NavigationContainerTests.kt +++ b/enro/src/androidTest/java/dev/enro/core/NavigationContainerTests.kt @@ -545,6 +545,7 @@ class NavigationContainerTests { .forward(GenericComposableKey("Five")) expectComposableContext { it.navigation.key.id == "Five" } + waitFor { activity.primaryContainer.isActive } scenario.recreate() activity = expectActivity() assertEquals(