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

Shivam Sethi

03/01/2021, 12:20 PM
Hello, how can I create a viewModel as in documentations using =viewModel() as default with a ViewModel with dependencies injected to it with Hilt ?
a

allan.conda

03/01/2021, 12:24 PM
just do it normally
Copy code
@Composable
fun DependentsScreen(
  viewModel: DependentsViewModel = viewModel()
)
s

Shivam Sethi

03/01/2021, 12:32 PM
I tried it it gave me error saying cannot initialize viewmodel with zero arguments ?
z

zhuinden

03/01/2021, 1:16 PM
Is your Activity annotated with @AndroidEntryPoint?
i

Ian Lake

03/01/2021, 2:00 PM
Are you within a
NavHost
created
composable
destination? Hilt has specific APIs for that in the
hilt-navigation
artifact: https://developer.android.com/jetpack/androidx/releases/hilt#1.0.0-alpha03
s

Shakil Karim

03/01/2021, 3:05 PM
i

Ian Lake

03/01/2021, 3:33 PM
That doesn't apply if you are using Navigation Compose, which already scopes ViewModels to your composable destination
s

Shakil Karim

03/01/2021, 5:10 PM
@Ian Lake Is there is a way to create viewModel now with only extension = viewModel() and still scope to compose and provide hilt dependencies on ViewModel when using Navigation Compose?
i

Ian Lake

03/01/2021, 5:12 PM
If you use
viewModel(HiltViewModelFactory(AmbientContext.current, backStackEntry))
like that page says
s

Shakil Karim

03/01/2021, 5:18 PM
Yup, i'm doing same as above, but wouldn't be better if we don't have to pass HiltViewModelFactory.
i

Ian Lake

03/01/2021, 5:24 PM
There's an upcoming
hilt-navigation-compose
artifact which will let you do `= hiltNavGraphViewModel()`: https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:hilt/hil[…]in/java/androidx/hilt/navigation/compose/NavHostController.kt
🙌 1
❤️ 2
s

Shivam Sethi

03/01/2021, 10:37 PM
Thanks for the responses, got it working 🎉
7 Views