Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
77 views
in Technique[技术] by (71.8m points)

android - What are differences creating viewmodels way?

I'm using viewModel in my project already. But ? know ? can initalize viewmodel with many ways. Do you know what are the differences between these ways?

  • viewModel = ViewModelProvider(this).get(ViewModelClass::class.java)
  • viewModel = ViewModelClass()
  • viewModel : ViewModelClass : by viewModels()
  • viewModel : ViewModelClass by ViewModelse{ ViewModelFactory(this,Reposityory(),intent }

What are the technical differences?

question from:https://stackoverflow.com/questions/65649963/what-are-differences-creating-viewmodels-way

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

By using

  • viewModel = ViewModelProvider(this).get(ViewModelClass::class.java) your are creating an instance of ViewModelClass scoped to this Fragment/activity and whenever the activity gets recreated same instance of the viewmodel is assigned rather than a new instance

  • viewModel = ViewModelClass() though it seems to be correct, it isn't . Whenever the activity gets recreated, new instance of viewmodel is assigned. Dont try to create an instance of ViewModel by directly calling its constructor, instead let the ViewModelProvider do the job.

  • viewModel: ViewModelClass by viewModels() courtesy of Android KTX here you delegate the creation of ViewModel . Its similar to

  val viewModel by lazy{
     ViewModelProvider(this).get(MyViewModel::class.java)
  }
  • viewModel : ViewModelClass by ViewModels{ ViewModelFactory(this,Reposityory(),intent)} its similar to
val viewModel by lazy {
    ViewModelProvider(this, ViewModelFactory(this,Reposityory(),intent)).get(MyViewModel::class.java)
}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...