Issue
The Code A is from the end branch of the official sample project.
The project use Hilt to implement dependency injection.
In my mind, I needn't to instance a ViewModel
class manually when I use Hilt, and the system will automatically instance a ViewModel
when it needs.
But It seems that the author use the code viewModel: MainViewModel = viewModel()
to instance the ViewModel
class manually in Code A, how can I instance a ViewMode
class automatically with Hilt when I use Compose?
Code A
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun CraneHomeContent(
onExploreItemClicked: OnExploreItemClicked,
openDrawer: () -> Unit,
modifier: Modifier = Modifier,
viewModel: MainViewModel = viewModel(),
) {
...
}
@HiltViewModel
class MainViewModel @Inject constructor(
private val destinationsRepository: DestinationsRepository,
@DefaultDispatcher private val defaultDispatcher: CoroutineDispatcher
) : ViewModel() {
...
}
Solution
As stated in the documentation
The viewModel() function mentioned in the ViewModel section automatically uses the ViewModel that Hilt constructs with the @HiltViewModel annotation. We've provided documentation with information about Hilt's ViewModel integration.
So as long as your viewmodel has the @HiltViewModel annotation, you don’t have to change anything.
Answered By - Karim0x1
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.