Skip to content

Commit cb811ec

Browse files
authored
Merge pull request #1728 from android/trambui/navigation-null-debug
incorporate safe fallback destination to fix null destination causing UI flickering
2 parents 81e7ef0 + 0e52982 commit cb811ec

File tree

1 file changed

+16
-3
lines changed
  • app/src/main/kotlin/com/google/samples/apps/nowinandroid/ui

1 file changed

+16
-3
lines changed

app/src/main/kotlin/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,15 @@ package com.google.samples.apps.nowinandroid.ui
1818

1919
import androidx.compose.runtime.Composable
2020
import androidx.compose.runtime.Stable
21+
import androidx.compose.runtime.collectAsState
22+
import androidx.compose.runtime.mutableStateOf
2123
import androidx.compose.runtime.remember
2224
import androidx.compose.runtime.rememberCoroutineScope
2325
import androidx.navigation.NavController
2426
import androidx.navigation.NavDestination
2527
import androidx.navigation.NavDestination.Companion.hasRoute
2628
import androidx.navigation.NavGraph.Companion.findStartDestination
2729
import androidx.navigation.NavHostController
28-
import androidx.navigation.compose.currentBackStackEntryAsState
2930
import androidx.navigation.compose.rememberNavController
3031
import androidx.navigation.navOptions
3132
import androidx.tracing.trace
@@ -83,9 +84,21 @@ class NiaAppState(
8384
userNewsResourceRepository: UserNewsResourceRepository,
8485
timeZoneMonitor: TimeZoneMonitor,
8586
) {
87+
private val previousDestination = mutableStateOf<NavDestination?>(null)
88+
8689
val currentDestination: NavDestination?
87-
@Composable get() = navController
88-
.currentBackStackEntryAsState().value?.destination
90+
@Composable get() {
91+
// Collect the currentBackStackEntryFlow as a state
92+
val currentEntry = navController.currentBackStackEntryFlow
93+
.collectAsState(initial = null)
94+
95+
// Fallback to previousDestination if currentEntry is null
96+
return currentEntry.value?.destination.also { destination ->
97+
if (destination != null) {
98+
previousDestination.value = destination
99+
}
100+
} ?: previousDestination.value
101+
}
89102

90103
val currentTopLevelDestination: TopLevelDestination?
91104
@Composable get() {

0 commit comments

Comments
 (0)