From 2664fbab2c897bb9f089a0ad41b12a27c590b6ab Mon Sep 17 00:00:00 2001 From: Tiago Pereira <> Date: Thu, 19 Oct 2023 10:15:34 +0100 Subject: [PATCH] Avoid composing scene multiple times due to BackStackEntry --- .../precompose/navigation/RouteBuilder.kt | 55 ++++++++++++++----- 1 file changed, 42 insertions(+), 13 deletions(-) diff --git a/precompose/src/commonMain/kotlin/moe/tlaster/precompose/navigation/RouteBuilder.kt b/precompose/src/commonMain/kotlin/moe/tlaster/precompose/navigation/RouteBuilder.kt index 27914c14..feed09f9 100644 --- a/precompose/src/commonMain/kotlin/moe/tlaster/precompose/navigation/RouteBuilder.kt +++ b/precompose/src/commonMain/kotlin/moe/tlaster/precompose/navigation/RouteBuilder.kt @@ -1,6 +1,9 @@ package moe.tlaster.precompose.navigation import androidx.compose.runtime.Composable +import androidx.compose.runtime.State +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember import moe.tlaster.precompose.navigation.route.FloatingRoute import moe.tlaster.precompose.navigation.route.GroupRoute import moe.tlaster.precompose.navigation.route.Route @@ -12,6 +15,24 @@ class RouteBuilder( ) { private val route = arrayListOf() + private fun sceneInternal( + route: String, + deepLinks: List, + navTransition: NavTransition?, + swipeProperties: SwipeProperties?, + content: @Composable (State) -> Unit, + ) { + addRoute( + SceneRoute( + route = route, + navTransition = navTransition, + deepLinks = deepLinks, + swipeProperties = swipeProperties, + content = { content(remember { mutableStateOf(it) }) }, + ), + ) + } + /** * Add the scene [Composable] to the [RouteBuilder] * @param route route for the destination @@ -26,14 +47,12 @@ class RouteBuilder( swipeProperties: SwipeProperties? = null, content: @Composable (BackStackEntry) -> Unit, ) { - addRoute( - SceneRoute( - route = route, - navTransition = navTransition, - deepLinks = deepLinks, - swipeProperties = swipeProperties, - content = content, - ), + sceneInternal( + route = route, + navTransition = navTransition, + deepLinks = deepLinks, + swipeProperties = swipeProperties, + content = { content(it.value) }, ) } @@ -74,6 +93,18 @@ class RouteBuilder( ) } + private fun floatingInternal( + route: String, + content: @Composable (State) -> Unit, + ) { + addRoute( + FloatingRoute( + route = route, + content = { content(remember { mutableStateOf(it) }) }, + ), + ) + } + /** * Add the floating [Composable] to the [RouteBuilder], which will show over the scene * @param route route for the destination @@ -83,11 +114,9 @@ class RouteBuilder( route: String, content: @Composable (BackStackEntry) -> Unit, ) { - addRoute( - FloatingRoute( - route = route, - content = content, - ), + floatingInternal( + route = route, + content = { content(it.value) }, ) }