
ViewModel LiveData 使用初体验
发布日期:2021-05-07 18:54:15
浏览次数:12
分类:技术文章
本文共 1937 字,大约阅读时间需要 6 分钟。
背景 Fragment 希望不用那么多代码在Fragment中。所以推出了ViewModel加载数据的方式。更加高度的解耦
生命周期
使用
package com.anguomob.love.activity.ui.myimport androidx.lifecycle.LiveDataimport androidx.lifecycle.MutableLiveDataimport androidx.lifecycle.ViewModelimport com.anguomob.love.bean.UserInfoimport com.anguomob.love.common.PassportManagerimport com.anguomob.love.net.usecase.PassportUseCaseimport io.reactivex.disposables.CompositeDisposableclass MyViewModel : ViewModel() { override fun onCleared() { super.onCleared() } private val _text = MutableLiveData() private val _error = MutableLiveData () var dataList: LiveData = _text var error: LiveData = _error val mDisposable: CompositeDisposable = CompositeDisposable() init { val subscribe = PassportUseCase().refreshUserInfo(PassportManager.getInstance().getUid()).subscribe({ it?.let { _text.value=it; } }, { _error.value=it }) mDisposable.add(subscribe) }}
创建 ViewModel 类 并直接加载数据
在Fragment中需要的地方
initData里面把代码用上
private lateinit var dashboardViewModel: MyViewModel
dashboardViewModel = ViewModelProvider(this).get(MyViewModel::class.java) dashboardViewModel.dataList.observe(viewLifecycleOwner, Observer { it?.let { PassportManager.getInstance().saveUserInfo(it) Glide.with(this) .load(it.avatar) .placeholder(getDefaultPlace(it.sex)) .transition(DrawableTransitionOptions.withCrossFade()) .into(mIvFDUpload) mTvFdNickName.text = it.nick_name; } }) dashboardViewModel.error.observe(viewLifecycleOwner, Observer { it?.let { TipsToast.showTips(activity, ApiErrorCodeDesc.getErrorMsg(it)) } })
发表评论
最新留言
路过按个爪印,很不错,赞一个!
[***.219.124.196]2025年04月01日 11时39分19秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
文本读取和csv文件生成工具类的编写
2019-03-04
@Import注解---导入资源
2019-03-04
Leetcode 面试题 08.04. 幂集(DAY 103) ---- 回溯算法学习期
2019-03-04
重读&笔记系列-《Linux多线程服务端编程》第一章
2019-03-04
解决ubuntu在虚拟机(VMware)环境下不能联网的问题
2019-03-04
LeetCode - 字符串相乘
2019-03-04
maya里创建不同颜色大小的HeadsUpDisplay的效果
2019-03-04
python 导航栏
2019-03-04
Python根据程序名称结束进程
2019-03-04
C# 适配器模式
2019-03-04
二分查找与插入排序的结合使用
2019-03-04
71 简化路径(模拟、栈)
2019-03-04
892 三维形体的表面积(分析)
2019-03-04
40. 组合总和 II(dfs、set去重)
2019-03-04
16 最接近的三数之和(排序、双指针)
2019-03-04
1333 餐厅过滤器(treemap映射)
2019-03-04
python中的all函数
2019-03-04
1137 第 N 个泰波那契数(迭代、记忆性递归)
2019-03-04
279 完全平方数(dfs)
2019-03-04
279 完全平方数(bfs)
2019-03-04