Home > other >  Why is viewModel() used in a composabe and viewModels() in an activity or fragment?
Why is viewModel() used in a composabe and viewModels() in an activity or fragment?

Time:11-06

In this link it is instructed to use viewModel() in any composable and in an activity, we will get the same object while calling viewModel(). Although it is instructed to use viewModel() inside a composable, I was able to use it in setContent{} (outside of any composable) also.

In this link it is instructed to use viewModels() in an activity or a fragment to get the object of a class that extends ViewModel.

In both of the cases, we are getting an object of a class that extends ViewModel. So, why do we need to use two different approaches (viewModel() and viewModels())?

CodePudding user response:

If you ask if you can use only viewModel without viewModels in Compose, the answer is yes. But in some cases it is more convenient to use both of them.

viewModels belongs to the androidx.activity package, is an extension to ComponentActivity, and has nothing to do with Compose. It was used in view-based Android and can still be used with Compose when you need to initialize or update your view model with some activity-specific callbacks.

In turn, viewModel is part of Compose and allows you to easily create/access a view model from any Composable.

You can call it directly inside setContent since it already belongs to the composable scope, but you would not be as comfortable calling it anywhere else in the activity, such as in onActivityResult(I know it's deprecated, it's just an example). You can still do it as shown in this answer, but in some cases viewModels may be easier to use.

  • Related