1

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?

1

1 Answer 1

2

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)
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.