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

Shakil Karim

02/02/2021, 7:56 AM
Is it possible to bind ViewModel with NavHost/NavGraph in Compose only app with zero fragments?
👌 1
s

satyan

02/02/2021, 8:56 AM
NavController
has a
getViewModelStoreOwner
with which you can retrieve a view model (via a
ViewModelProvider
) Maybe you can try this way 🤷 https://developer.android.com/reference/androidx/navigation/NavController#getViewModelStoreOwner(int)
d

darkmoon_uk

02/02/2021, 10:13 AM
Yes I am doing this in my current project. You only need one initial Activity which uses
setContent { ... }
to open a Composable scope. From here you can use NavHost/Controller as per the documentation. Developer interaction with Activity is minimal, and interaction with Fragments is none. I'm actually using two nested NavHosts; one manages the top-level flow of the App, another handles bottom-bar navigation, between content panes within the main screen. In summary; a 'normally complex' App navigation, made purely in Compose. For ViewModels I'm currently accessing a
ViewModelProvider.Factory
from Ambient, but this might be better moved to NavController as @satyan said.
s

Shakil Karim

02/02/2021, 10:57 AM
"For ViewModels I'm currently accessing a 
ViewModelProvider.Factory
 from Ambient" Do you have any sample code for this?
9 Views