Search code examples
androidandroid-jetpack-composeandroid-viewmodel

Can Jetpack viewmodel be instantiated in composable function?


Android documentation says that composable functions can run in parallel: https://developer.android.com/jetpack/compose/mental-model#parallel

It means, that any specific composable function can be called on any thread.

Then if we instantiate viewModel as follows:

@Composable
fun FooScreen(viewModel: FooViewModel = viewModel()) {
    ...
}

It means, that viewModel() (androidx.lifecycle.viewmodel.compose.viewModel) can be called on any thread (in particular, on background thread).

Next, if we dig into what viewModel() does, it turns out, that it calls ViewModelProvider#get. And ViewModelProvider#get, in turn, is marked with @MainThread annotation.

Does it mean, that we cannot call viewModel() inside composable functions?


Solution

  • The docs say can be multi-threaded. They are currently not multi-threaded - composition always runs on the main thread.

    There is an existing feature request for ViewModels specifically to support multi-threaded creation of ViewModels that says:

    This would be particularly helpful for cases such as with the Lifecycle ViewModel Compose API of viewModel(), which would ensure future compatibility for multi-threaded composition.