博客
关于我
ViewModel LiveData 使用初体验
阅读量:355 次
发布时间:2019-03-04

本文共 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))            }        })

 

转载地址:http://cwpr.baihongyu.com/

你可能感兴趣的文章
LiveGBS user/save 逻辑缺陷漏洞复现(CNVD-2023-72138)
查看>>
localhost:5000在MacOS V12(蒙特利)中不可用
查看>>
logstash mysql 准实时同步到 elasticsearch
查看>>
Luogu2973:[USACO10HOL]赶小猪
查看>>
mabatis 中出现< 以及> 代表什么意思?
查看>>
Mac book pro打开docker出现The data couldn’t be read because it is missing
查看>>
MAC M1大数据0-1成神篇-25 hadoop高可用搭建
查看>>
mac mysql 进程_Mac平台下启动MySQL到完全终止MySQL----终端八步走
查看>>
Mac OS 12.0.1 如何安装柯美287打印机驱动,刷卡打印
查看>>
MangoDB4.0版本的安装与配置
查看>>
Manjaro 24.1 “Xahea” 发布!具有 KDE Plasma 6.1.5、GNOME 46 和最新的内核增强功能
查看>>
mapping文件目录生成修改
查看>>
MapReduce程序依赖的jar包
查看>>
mariadb multi-source replication(mariadb多主复制)
查看>>
MariaDB的简单使用
查看>>
MaterialForm对tab页进行隐藏
查看>>
Member var and Static var.
查看>>
memcached高速缓存学习笔记001---memcached介绍和安装以及基本使用
查看>>
memcached高速缓存学习笔记003---利用JAVA程序操作memcached crud操作
查看>>
Memcached:Node.js 高性能缓存解决方案
查看>>