Inject ViewModels into Composable
Koject can inject Android ViewModels into Composable.
LINK
Please also refer the documentation for details on ViewModel, such as how to inject ViewModel into Activity / Fragment.
Setup to use ViewModels in Compose
To inject ViewModels into Composable, add the following dependencies:
dependencies {
implementation("com.moriatsushi.koject:koject-compose-viewmodel:1.3.0")
}
Please also refer to the Setup document.
Using ViewModels in Compose
Specify the @ViewModelComponent
and @Provides
annotations when defining a ViewModel.
As with other providing types, constructor injection is available.
@Provides
@ViewModelComponent
class TopViewModel(
private val userRepository: UserRepository,
private val contentRepository: ContentRepository,
): ViewModel() {
/* ... */
}
When using ViewModels, use the injectViewModel()
Composable function.
@Composable
fun TopPage(
viewModel: TopViewModel = injectViewModel()
) {
/* ... */
}