Archie
04/20/2026, 8:46 AMNavBackStack really is just a List<T> , I always wonder if it could be part of the Dependency Graph so it could be injected to like a ViewModel . But if I do add it to the graph, same with this implementation here, I now lose the ability to restore the state of the NavBackStack. I just wonder whats the advise here? Should it be part of the DI or should it stack within the compose scope?Albert Chang
04/20/2026, 10:02 AMNavBackStack.
You don't. You can use something like this to save/restore the back stack.
@Provides
@ActivityScoped
fun provideBackStack(
@ActivityContext context: Context,
): BackStack {
val activity = context as ComponentActivity
val backStack = activity.savedStateRegistry.consumeRestoredStateForKey(KEY)?.let {
// Restore back stack
} ?: BackStack()
activity.savedStateRegistry.registerSavedStateProvider(KEY) {
SavedState().apply {
// Save back stack
}
}
return backStack
}Archie
04/20/2026, 10:20 AMArchie
04/20/2026, 10:44 AMAlbert Chang
04/20/2026, 12:37 PM@Provides
@ActivityScoped
fun provideBackStack(
@ActivityContext context: Context,
): BackStack {
val activity = context as ComponentActivity
return ViewModelProvider.create(
activity.viewModelStore,
activity.defaultViewModelProviderFactory,
activity.defaultViewModelCreationExtras,
)[BackStackViewModel::class.java].backStack
}
private class BackStackViewModel(savedStateHandle: SavedStateHandle) : ViewModel() {
val backStack by savedStateHandle.saveable(saver = BackStack.Saver) {
BackStack()
}
}Archie
04/20/2026, 12:44 PMefemoney
04/20/2026, 3:32 PMArchie
04/21/2026, 3:52 AM