ViewModel
- LiveData和ViewModel是一对好搭档
定义
- 视图模型,以感知生命周期的形式来存储和管理视图相关的数据,让数据可在发生屏幕旋转等配置更改后继续留存;
特点
- 页面数据丢失(转屏、闪退等生命周期重建现象),可以使用onSaveInstanceState()保存数据,单仅适用于数据量少(IPC对Bundle有1M的限制),且需要支持序列化,而ViewModel对数据量和序列化均没有要求(ViewModel生命周期长于Activity);
- 有效的将逻辑代码和视图控制器分开,防止视图控制器臃肿;
- 逻辑层往往持有UI层引用并进行异步调用,而UI需要管理这些请求,确保界面销毁后不会存在内存泄露,而ViewModel可以避免(ViewModel不持有UI层引用);
生命周期
- ViewModelScope
- Activity created
- onCreated()
- onStart()
- onResume()
- Activity rotated
- onPause()
- onStop()
- onDestroy()
- onCreated()
- onStart()
- onResume()
- Activity finish()
- onPause()
- onStop()
- onDestroy()
- Activity created
- onCleared
- Activity finished
简单使用
//1. 自定义ViewModel
//class MyViewModel(application: Application) : AndroidViewModel(application) {
class UserViewModel : ViewModel() {
var userName: MutableLiveData = MutableLiveData()
var isLoading: MutableLiveData = MutableLiveData()
//2. 获取数据的异步请求
fun getUserName() {
isLoading.value = true
GlobalScope.launch {
delay(1000)
//3.使用LiveData将数据抛出
isLoading.postValue(false)
userName.postValue("欢迎关注公众号:今阳说")
}
}
}
class ViewModelActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_view_model)
//4. 获取ViewModel实例
val userViewModel: UserViewModel = ViewModelProvider(
this, ViewModelProvider.NewInstanceFactory()
// this, ViewModelProvider.AndroidViewModelFactory(application)
).get(UserViewModel::class.java)
//5. 观察ViewModel中的LiveData数据,更新UI
userViewModel.userName.observe(this, Observer {
tv_view_model.text=it
})
userViewModel.isLoading.observe(this, Observer {
progressBar.visibility=if (it) View.VISIBLE else View.GONE
})
userViewModel.getUserName()
}
}
- 还可以用来在不同Fragment/Activity之间共享数据,类似于RxBus等事件总线,都是基于观察者模式
class SharedViewModel :ViewModel(){
var isReadFinish: MutableLiveData = MutableLiveData()
}
class DetailFragment : Fragment(){
fun onReadFinish(){
val viewModel=ViewModelProvider(
this, ViewModelProvider.NewInstanceFactory()
).get(SharedViewModel::class.java)
viewModel.isReadFinish.value=true
}
}
class ListFragment : Fragment(){
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val viewModel=ViewModelProvider(
this, ViewModelProvider.NewInstanceFactory()
).get(SharedViewModel::class.java)
viewModel.isReadFinish.observe(this, Observer {
//更新列表UI
})
}
}
ViewModel原理解析
ViewModel类
- 先看一下ViewModel类的代码
public abstract class ViewModel {
// Can't use ConcurrentHashMap, because it can lose values on old apis (see b/37042460)
@Nullable
private final Map mBagOfTags = new HashMap<>();
private volatile boolean mCleared = false;
/**
* This method will be called when this ViewModel is no longer used and will be destroyed.
*
* It is useful when ViewModel observes some data and you need to clear this subscription to * prevent a leak of this ViewModel. */ @SuppressWarnings(“WeakerAccess”) protected void onCleared() { //在ViewModel将被清除时调用 //当ViewModel观察了一些数据,可以在这里做解注册 防止内存泄漏 } //在ViewModel将被清除时调用 @MainThread final void clear() { mCleared = true; // Since clear() is final, this method is still called on mock objects // and in those cases, mBagOfTags is null. It’ll always be empty though // because setTagIfAbsent and getTag are not final so we can skip // clearing it if (mBagOfTags != null) { synchronized (mBagOfTags) { for (Object value : mBagOfTags.values()) { // see comment for the similar call in setTagIfAbsent closeWithRuntimeException(value); } } } onCleared(); } … }
ViewModelProvider类
- 使用ViewModel时我们是通过ViewModelProvider获取其实例对象的,那么我们来看一下ViewModelProvider的构造方法;
- 由下面代码可以看出就是通过反射生成ViewModel的实现类;
public ViewModelProvider(@NonNull ViewModelStoreOwner owner, @NonNull Factory factory) {
this(owner.getViewModelStore(), factory);
}
public ViewModelProvider(@NonNull ViewModelStore store, @NonNull Factory factory) {
mFactory = factory;
mViewModelStore = store;
}
ViewModelProvider如何通过ViewModelStore实现配置更改重建后ViewModel依然存在的
- 上面ViewModelProvider构造方法的第一个参数通过owner.getViewModelStore()获取ViewModelStore对象,那么我们来看一下ComponentActivity中对ViewModelStoreOwner的实现:
@NonNull
@Override
public ViewModelStore getViewModelStore() {
if (getApplication() == null) {
throw new IllegalStateException("Your activity is not yet attached to the "
+ "Application instance. You can't request ViewModel before onCreate call.");
}
if (mViewModelStore == null) {
NonConfigurationInstances nc =
(NonConfigurationInstances) getLastNonConfigurationInstance();
if (nc != null) {
// Restore the ViewModelStore from NonConfigurationInstances
mViewModelStore = nc.viewModelStore;
}
if (mViewModelStore == null) {
mViewModelStore = new ViewModelStore();
}
}
return mViewModelStore;
}
- 上面代码先从NonConfigurationInstance从获取ViewModelStore实例,如果不存在,就new ViewModelStore();
- 而在onRetainNonConfigurationInstance()方法中会把mViewModelStore赋值给NonConfigurationInstances;
- 在Activity因配置改变 而正要销毁时,且新Activity会立即创建,那么系统就会调用此方法。
- 也就说配置改变时系统把viewModelStore存在了NonConfigurationInstances中。
@Override
@Nullable
public final Object onRetainNonConfigurationInstance() {
Object custom = onRetainCustomNonConfigurationInstance();
ViewModelStore viewModelStore = mViewModelStore;
if (viewModelStore == null) {
// No one called getViewModelStore(), so see if there was an existing
// ViewModelStore from our last NonConfigurationInstance
NonConfigurationInstances nc =
(NonConfigurationInstances) getLastNonConfigurationInstance();
if (nc != null) {
viewModelStore = nc.viewModelStore;
}
}
if (viewModelStore == null && custom == null) {
return null;
}
NonConfigurationInstances nci = new NonConfigurationInstances();
nci.custom = custom;
nci.viewModelStore = viewModelStore;
return nci;
}
- 可以看到getViewModelStore和onRetainNonConfigurationInstance中都是通过getLastNonConfigurationInstance获取NonConfigurationInstances对象的
@Nullable
public Object getLastNonConfigurationInstance() {
return mLastNonConfigurationInstances != null
? mLastNonConfigurationInstances.activity : null;
}
- 那么mLastNonConfigurationInstances是哪来的呢?是Activity的attach方法
- attach方法是为Activity关联上下文环境,是在Activity 启动的核心流程——ActivityThread的performLaunchActivity方法中调用,这里的lastNonConfigurationInstances是存在 ActivityClientRecord中的一个组件信息;
- 那么ActivityThread 中的 ActivityClientRecord 是不受 activity 重建的影响,那么ActivityClientRecord中lastNonConfigurationInstances也不受影响,那么其中的Object activity也不受影响,那么ComponentActivity中的NonConfigurationInstances的viewModelStore不受影响,那么viewModel也就不受影响了。
final void attach(Context context, ActivityThread aThread, ...
NonConfigurationInstances lastNonConfigurationInstances,... ) {
...
mLastNonConfigurationInstances = lastNonConfigurationInstances;
...
}
ViewModelProvider的Factory如何使用
- ViewModelProvider构造方法的第二个入参Factory,在ViewModelProvider中已经实现了两个供我们使用:NewInstanceFactory和AndroidViewModelFactory
/**
* Simple factory, which calls empty constructor on the give class.
*/
public static class NewInstanceFactory implements Factory {
@SuppressWarnings("ClassNewInstance")
@NonNull
@Override
public T create(@NonNull Class modelClass) {
//noinspection TryWithIdenticalCatches
try {
return modelClass.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException("Cannot create an instance of " + modelClass, e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Cannot create an instance of " + modelClass, e);
}
}
}
/**
* {@link Factory} which may create {@link AndroidViewModel} and
* {@link ViewModel}, which have an empty constructor.
*/
public static class AndroidViewModelFactory extends ViewModelProvider.NewInstanceFactory {
private static AndroidViewModelFactory sInstance;
/**
* Retrieve a singleton instance of AndroidViewModelFactory.
*
* @param application an application to pass in {@link AndroidViewModel}
* @return A valid {@link AndroidViewModelFactory}
*/
@NonNull
public static AndroidViewModelFactory getInstance(@NonNull Application application) {
if (sInstance == null) {
sInstance = new AndroidViewModelFactory(application);
}
return sInstance;
}
private Application mApplication;
/**
* Creates a {@code AndroidViewModelFactory}
*
* @param application an application to pass in {@link AndroidViewModel}
*/
public AndroidViewModelFactory(@NonNull Application application) {
mApplication = application;
}
@NonNull
@Override
public T create(@NonNull Class modelClass) {
if (AndroidViewModel.class.isAssignableFrom(modelClass)) {
//noinspection TryWithIdenticalCatches
try {
return modelClass.getConstructor(Application.class).newInstance(mApplication);
} catch (NoSuchMethodException e) {
throw new RuntimeException("Cannot create an instance of " + modelClass, e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Cannot create an instance of " + modelClass, e);
} catch (InstantiationException e) {
throw new RuntimeException("Cannot create an instance of " + modelClass, e);
} catch (InvocationTargetException e) {
throw new RuntimeException("Cannot create an instance of " + modelClass, e);
}
}
return super.create(modelClass);
}
}
- 如果需要参数,也可以自己实现Factory,例如:
public class MainViewModelFactory implements ViewModelProvider.Factory {
private String mValue;
public MainViewModelFactory(String value){
mValue = value;
}
@NonNull
@Override
public T create(@NonNull Class modelClass) {
try {
Class[] parameterTypeArray = new Class[]{String.class};
return modelClass.getConstructor(parameterTypeArray).newInstance(mValue);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
}
//或者多个参数的
class ParametrizedFactory implements ViewModelProvider.Factory {
private final Object[] mConstructorParams;
ParametrizedFactory(Object... constructorParams) {
mConstructorParams = constructorParams;
}
@Override
public T create(Class modelClass) {
if (modelClass == null) {
throw new IllegalArgumentException("Target ViewModel class can not be null")
}
Log.w("ParametrizedFactory", "Don't use callbacks or Context parameters in order to avoid leaks!!")
try {
if (mConstructorParams == null || mConstructorParams.length == 0) {
return modelClass.newInstance();
} else {
Class>[] classes = new Class>[mConstructorParams.length];
for (int i = 0; i < mConstructorParams.length; i++) {
classes[i] = mConstructorParams[i].getClass();
}
return modelClass.getConstructor(classes).newInstance(mConstructorParams);
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
}
ViewModelProvider的get()是如何获取ViewModel的
- 下面让我们再看一下ViewModelProvider的get()是如何实现的
@NonNull
@MainThread
public T get(@NonNull Class modelClass) {
String canonicalName = modelClass.getCanonicalName();
if (canonicalName == null) {
throw new IllegalArgumentException("Local and anonymous classes can not be ViewModels");
}
return get(DEFAULT_KEY + ":" + canonicalName, modelClass);
}
//带key创建ViewModel,会让使用相同key的Activity或者Fragment,创建的ViewModel数据独立
@NonNull
@MainThread
public T get(@NonNull String key, @NonNull Class modelClass) {
//1.通过key在ViewModelStore中取得ViewModel;
//2.如果这个ViewModel能转换为modelClass类的对象,直接返回该ViewModel;
//3.否则会通过Factory创建一个ViewModel,并将其存储到ViewModelStore中;
ViewModel viewModel = mViewModelStore.get(key);
if (modelClass.isInstance(viewModel)) {
//noinspection unchecked
return (T) viewModel;
} else {
//noinspection StatementWithEmptyBody
if (viewModel != null) {
// TODO: log a warning.
}
}
if (mFactory instanceof KeyedFactory) {
viewModel = ((KeyedFactory) (mFactory)).create(key, modelClass);
} else {
viewModel = (mFactory).create(modelClass);
}
mViewModelStore.put(key, viewModel);
//noinspection unchecked
return (T) viewModel;
}
ViewModelStore类
- 上面提到将ViewModel存储到ViewModelStore中,那么我们来看一下是如何存储的
public class ViewModelStore {
private final HashMap mMap = new HashMap<>();
final void put(String key, ViewModel viewModel) {
ViewModel oldViewModel = mMap.put(key, viewModel);
if (oldViewModel != null) {
oldViewModel.onCleared();
}
}
final ViewModel get(String key) {
return mMap.get(key);
}
Set keys() {
return new HashSet<>(mMap.keySet());
}
/**
* Clears internal storage and notifies ViewModels that they are no longer used.
*/
public final void clear() {
for (ViewModel vm : mMap.values()) {
vm.clear();
}
mMap.clear();
}
}
1、本站所有资源均从互联网上收集整理而来,仅供学习交流之用,因此不包含技术服务请大家谅解!
2、本站不提供任何实质性的付费和支付资源,所有需要积分下载的资源均为网站运营赞助费用或者线下劳务费用!
3、本站所有资源仅用于学习及研究使用,您必须在下载后的24小时内删除所下载资源,切勿用于商业用途,否则由此引发的法律纠纷及连带责任本站和发布者概不承担!
4、本站站内提供的所有可下载资源,本站保证未做任何负面改动(不包含修复bug和完善功能等正面优化或二次开发),但本站不保证资源的准确性、安全性和完整性,用户下载后自行斟酌,我们以交流学习为目的,并不是所有的源码都100%无错或无bug!如有链接无法下载、失效或广告,请联系客服处理!
5、本站资源除标明原创外均来自网络整理,版权归原作者或本站特约原创作者所有,如侵犯到您的合法权益,请立即告知本站,本站将及时予与删除并致以最深的歉意!
6、如果您也有好的资源或教程,您可以投稿发布,成功分享后有站币奖励和额外收入!
7、如果您喜欢该资源,请支持官方正版资源,以得到更好的正版服务!
8、请您认真阅读上述内容,注册本站用户或下载本站资源即您同意上述内容!
原文链接:https://www.dandroid.cn/archives/19311,转载请注明出处。
评论0