ViewModel is designed to store and manage UI-related data in a lifecycle conscious way
Copied from https://codelabs.developers.google.com/codelabs/build-app-with-arch-components/index.html#8
Android Developers Video of Architecture Components: ViewModel
The ViewModel class is designed to hold and manage UI-related data in a life-cycle conscious way. This allows data to survive configuration changes such as screen rotations. By separating out the UI data from the UI controllers, you can create a separation of responsibilities: ViewModels deal with providing, manipulating and storing UI state and UI Controllers deal with displaying the state. ViewModels : 简言之就是以 LiveData 方式持有并管理 UI 相关数据和状态,使得 UI 只负责展示数据。
ViewModel 需要获取 Repository 的引用:ViewModel doesn't have a reference to a SunshineRepository, the most testable way to design the code is to pass an instance of the SunshineRepository into the DetailActivityViewModel.
ViewModel 通过 ViewModelProvider.of(this).get(ViewModel.class)
构造,但这个调用的是 ViewModel的没有参数的默认构造器,为了解决这个问题,需要定义一个 view model provider factory.
ViewModel Provider takes an activity instance, this is the mechanism that allows you to rotate the phone, get a technically new activity instance, but insure that instance is always associated with the same ViewModel.
So never pass context into ViewModel instances. Do not store Activity, Fragment, or View instances or their Context in the ViewModel, otherwise you end up with references that point to the destroyed Activity. This is a memory leak.