0

I have an Android ViewModel

class MyVM: ViewModel()

In my activity, I can create an instance of MyVM using either:

val viewModel = MyVM()

or using:

val viewModel = ViewModelProvider(this).get(MyVM::class.java)

They both work as expected. My question is what are the main differences between the two

T D Nguyen
  • 7,054
  • 4
  • 51
  • 71
  • https://developer.android.com/topic/libraries/architecture/viewmodel#lifecycle – IR42 Mar 25 '22 at 08:30
  • [enter link description here](https://stackoverflow.com/questions/46283981/android-viewmodel-additional-arguments) This has been answered here – LuongXuanNam Mar 25 '22 at 10:43
  • This has been answered here [android-viewmodel-additional-arguments](https://stackoverflow.com/questions/46283981/android-viewmodel-additional-arguments) – LuongXuanNam Mar 25 '22 at 10:44
  • 1
    If you directly call the constructor instead of going through the ViewModelProvider, it will not be cached and survive screen rotations or Fragment restoration. It will not go through its lifecycle functions. There would be no point in making it a subclass of ViewModel at all because you wouldn’t be using any of the ViewModel features. – Tenfour04 Mar 25 '22 at 11:42

0 Answers0