Home > front end >  Create multiple view model instances in Jetpack Compose
Create multiple view model instances in Jetpack Compose

Time:09-30

We know that the following way to create an instance is very good, you can enjoy life cycle management. And the instances created in an ViewModel are the same.

But if you want to create two instances on one page, how to create it?

fun Following(viewModel: FollowViewModel = viewModel()) {

}

CodePudding user response:

You can use key argument which is used to identify the ViewModel:

val firstViewModel = viewModel<FollowViewModel>(key = "first")
val secondViewModel = viewModel<FollowViewModel>(key = "second")

p.s. If you are using Hilt, hiltViewModel does not yet support keys, you can star this feature request for updates.

  • Related