3

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()) {

}
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
gaohomway
  • 2,132
  • 1
  • 20
  • 37

1 Answers1

12

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, and check out hack in this answer for now.

Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
  • Hi! Dukhov! I can always see you and solved my problem again, thank you very much. If I want to get the key in ViewModel, is there a way? – gaohomway Sep 29 '21 at 06:52
  • @weifans You're welcome=) I don't think so. But using a `factory` argument you can create your view model object with the needed key as a parameter. – Phil Dukhov Sep 29 '21 at 07:26