https://kotlinlang.org logo
#compose
Title
# compose
s

Se7eN

10/31/2020, 1:21 PM
I'm getting different instances of a view model in different screens of the same
NavHost
. Is this intended? How can I scope the view models to the
NavHost
or activity?
Copy code
NavHost(navController = navController, startDestination = "screen1") {
    composable("screen1") { Screen1() }
    composable("screen2") { Screen2() }
}

@Composable fun Screen1() {
    val viewModel: MainViewModel = viewModel()
}

@Composable fun Screen2() {
    val viewModel: MainViewModel = viewModel()
}
Without passing them as arguments
i

Ian Lake

10/31/2020, 2:08 PM
Create your ViewModel outside of the NavHost if you want it scoped outside of the individual screen
✔️ 1
g

Grigorii Yurkov

10/31/2020, 2:12 PM
Do you mean create once and pass trough arguments?
s

Se7eN

10/31/2020, 3:09 PM
Okay thanks Yes @Grigorii Yurkov
a

Alexjlockwood

10/31/2020, 5:15 PM
Are there any example projects that make use of this library yet? Jw
i

Ian Lake

10/31/2020, 6:11 PM
@John O'Reilly has updated his apps to use it: https://twitter.com/joreilly/status/1321518153264959489?s=19
2 Views