From 827d3d66e2e765f9e257c8031a29fe84fc2256e0 Mon Sep 17 00:00:00 2001 From: Tram Bui Date: Tue, 10 Dec 2024 11:24:53 -0800 Subject: [PATCH] incorporate safe fallback destination to null destination UI flickering --- .../apps/nowinandroid/ui/NiaAppState.kt | 19 ++++++++++++++++--- gradle/libs.versions.toml | 2 +- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/app/src/main/kotlin/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt b/app/src/main/kotlin/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt index 249f07590..7c892c854 100644 --- a/app/src/main/kotlin/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt +++ b/app/src/main/kotlin/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt @@ -18,6 +18,8 @@ package com.google.samples.apps.nowinandroid.ui import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.navigation.NavController @@ -25,7 +27,6 @@ import androidx.navigation.NavDestination import androidx.navigation.NavDestination.Companion.hasRoute import androidx.navigation.NavGraph.Companion.findStartDestination import androidx.navigation.NavHostController -import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import androidx.navigation.navOptions import androidx.tracing.trace @@ -83,9 +84,21 @@ class NiaAppState( userNewsResourceRepository: UserNewsResourceRepository, timeZoneMonitor: TimeZoneMonitor, ) { + private val previousDestination = mutableStateOf(null) + val currentDestination: NavDestination? - @Composable get() = navController - .currentBackStackEntryAsState().value?.destination + @Composable get() { + // Collect the currentBackStackEntryFlow as a state + val currentEntry = navController.currentBackStackEntryFlow + .collectAsState(initial = null) + + // Fallback to previousDestination if currentEntry is null + return currentEntry.value?.destination.also { destination -> + if (destination != null) { + previousDestination.value = destination + } + } ?: previousDestination.value + } val currentTopLevelDestination: TopLevelDestination? @Composable get() { diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 07076ca7d..7dc96d65a 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -17,7 +17,7 @@ androidxHiltNavigationCompose = "1.2.0" androidxLifecycle = "2.8.6" androidxMacroBenchmark = "1.3.0" androidxMetrics = "1.0.0-beta01" -androidxNavigation = "2.8.0" +androidxNavigation = "2.8.4" androidxProfileinstaller = "1.3.1" androidxTestCore = "1.6.1" androidxTestExt = "1.2.1"