@@ -19,6 +19,7 @@ package com.example.nav3recipes.passingarguments.injectedviewmodels
19
19
import android.os.Bundle
20
20
import androidx.activity.ComponentActivity
21
21
import androidx.activity.compose.setContent
22
+ import androidx.compose.foundation.lazy.LazyColumn
22
23
import androidx.compose.material3.Button
23
24
import androidx.compose.material3.Text
24
25
import androidx.compose.runtime.Composable
@@ -34,6 +35,7 @@ import androidx.navigation3.ui.NavDisplay
34
35
import androidx.navigation3.ui.rememberSceneSetupNavEntryDecorator
35
36
import com.example.nav3recipes.content.ContentBlue
36
37
import com.example.nav3recipes.content.ContentGreen
38
+ import com.example.nav3recipes.passingarguments.basicviewmodels.RouteB
37
39
import com.example.nav3recipes.ui.setEdgeToEdgeConfig
38
40
import dagger.assisted.Assisted
39
41
import dagger.assisted.AssistedFactory
@@ -63,6 +65,11 @@ class InjectedViewModelsActivity : ComponentActivity() {
63
65
NavDisplay (
64
66
backStack = backStack,
65
67
onBack = { backStack.removeLastOrNull() },
68
+
69
+ // In order to add the `ViewModelStoreNavEntryDecorator` (see comment below for why)
70
+ // we also need to add the default `NavEntryDecorator`s as well. These provide
71
+ // extra information to the entry's content to enable it to display correctly
72
+ // and save its state.
66
73
entryDecorators = listOf (
67
74
rememberSceneSetupNavEntryDecorator(),
68
75
rememberSavedStateNavEntryDecorator(),
@@ -71,15 +78,27 @@ class InjectedViewModelsActivity : ComponentActivity() {
71
78
entryProvider = entryProvider {
72
79
entry<RouteA > {
73
80
ContentGreen (" Welcome to Nav3" ) {
74
- Button (onClick = {
75
- backStack.add(RouteB (" 123" ))
76
- }) {
77
- Text (" Click to navigate" )
81
+ LazyColumn {
82
+ items(10 ) { i ->
83
+ Button (onClick = {
84
+ backStack.add(RouteB (" $i " ))
85
+ }) {
86
+ Text (" $i " )
87
+ }
88
+ }
78
89
}
79
90
}
80
91
}
81
92
entry<RouteB > { key ->
82
93
val viewModel = hiltViewModel<RouteBViewModel , RouteBViewModel .Factory >(
94
+ // Note: We need a new ViewModel for every new RouteB instance. Usually
95
+ // we would need to supply a `key` String that is unique to the
96
+ // instance, however, the ViewModelStoreNavEntryDecorator (supplied
97
+ // above) does this for us, using `NavEntry.contentKey` to uniquely
98
+ // identify the viewModel.
99
+ //
100
+ // tl;dr: Make sure you use rememberViewModelStoreNavEntryDecorator()
101
+ // if you want a new ViewModel for each new navigation key instance.
83
102
creationCallback = { factory ->
84
103
factory.create(key)
85
104
}
0 commit comments