Search code examples
androidkotlinandroid-jetpack-composeandroid-viewmodeldagger-hilt

How to inject a ViewModel object in composable functions?


I have an app where I inject a ViewModel object directly in the MainScreen:

@Composable
fun MainScreen(
    viewModel: ItemsViewModel = hiltViewModel()
) {
    Scaffold(
        topBar = {
            TopBar(
                onClick = {
                    viewModel.signOut()
                }
            )
        },
        content = {
            ItemsContent(
                items = viewModel.getItems()
            )
        },
        floatingActionButton = {
            FAB(
                onClick = {
                    viewModel.addItem("ABC")
                }
            )
        }
    )
}

Is it recommended to inject the ViewModel object only once in the MainScreen screen or is it ok if I inject the same ViewModel object inside each composable function, TopBar, ItemsContent and FAB?


Solution

  • You should keep your composables as independent as possible from view models. That means that you usually only want your top-most composables (your Screens) to hold an instance of the view model. Everything below that only receives the states and callbacks of the view model that it actually needs, passed as parameters.

    The way you did it in your question looks good. This way the other composables have simple parameters and can be more easily tested and reused.