当前位置:网站首页>ViewModel 记录下 +
ViewModel 记录下 +
2022-08-03 06:34:00 【清风徐来辽】
特点:
- 单一职责,将数据从业务中抽离出来。即只要是界面上看的到的数据,相关变量都应该存放在ViewModel,而不是Activity中
- 生命周期长,存在于所属对象(Activity,Fragment)的全部生命周期
- 扩展性好,方便与其他功能组合,例如Livedata,room.
使用场景:
- 横竖屏切换,Activity重建,数据可依然保存
- 同一个Activity下,Fragment之间的数据共享
应用事例:
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
public class BookChargeVM extends AndroidViewModel {
private MutableLiveData<Boolean> initReuslt = new MutableLiveData();
public BookChargeVM(@NonNull Application application) {
super(application);
}
public LiveData<Boolean> getInitResult() {
return this.initReuslt;
}
}
@Route(path = "/main/AndroidViewModelActivity")
public class AndroidViewModelActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_view_model);
AppLogUtils.i(TAG,"onCreate --------------");
this.mVM.getInitResult().observe(this, (result) -> {
AppLogUtils.i(TAG,"result ===="+result);
});
}
private BookChargeVM mVM
= (BookChargeVM) ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication()).create(BookChargeVM.class);
}
AppLogUtils.i(TAG,"result ===="+result);
这行日志没有打出来,就是说initReuslt 未改变的情况下不会产生回调
支持协程
将 Kotlin 协程与生命周期感知型组件一起使用:https://developer.android.google.cn/topic/libraries/architecture/coroutines
参考地址
ViewModel简介:https://www.jianshu.com/p/105541cde280
ViewModel 使用及原理解析:https://blog.csdn.net/xfhy_/article/details/88703853
Android 开发者-文档-指南-ViewModel 概览:https://developer.android.google.cn/topic/libraries/architecture/viewmodel#java
边栏推荐
猜你喜欢
随机推荐
重量级大咖来袭:阿里云生命科学与智能计算峰会精彩内容剧透
【Shell】3万字图文讲解带你快速掌握shell脚本编程
安全狗云原生安全能力全面亮相全球数字经济大会暨ISC互联网安全大会
spark中Repartition 和 Coalesce 区别
学会可视化大屏布局技巧,让领导都赞不绝口
pyspark df 二次排序
【着色器实现Glow可控局部发光效果_Shader效果第十三篇】
MySQL忘记密码怎么办
drop database出现1010
信息学奥赛一本通T1448:深搜的剪枝技巧 电路维修
consul理解
链表之打基础--基本操作(必会)
El - tree set using setCheckedNodessetCheckedKeys default check nodes, and a new check through setChecked specified node
多线程打印ABC(继承+进阶)
postman将接口返回结果生成json文件到本地
调用feign报错openfeign/feign-core/10.4.0/feign-core-10.4.0.jar
用代码构建UI界面
pgaudit 的安装使用《postgresql》
模型训练前后显卡占用对比、多卡训练GPU占用分析【一文读懂】
信息学奥赛一本通T1447:靶形数独