博客
关于我
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/

你可能感兴趣的文章
MySQL 数据类型和属性
查看>>
mysql 敲错命令 想取消怎么办?
查看>>
Mysql 整形列的字节与存储范围
查看>>
mysql 断电数据损坏,无法启动
查看>>
MySQL 日期时间类型的选择
查看>>
Mysql 时间操作(当天,昨天,7天,30天,半年,全年,季度)
查看>>
MySQL 是如何加锁的?
查看>>
MySQL 是怎样运行的 - InnoDB数据页结构
查看>>
mysql 更新子表_mysql 在update中实现子查询的方式
查看>>
MySQL 有什么优点?
查看>>
mysql 权限整理记录
查看>>
mysql 权限登录问题:ERROR 1045 (28000): Access denied for user ‘root‘@‘localhost‘ (using password: YES)
查看>>
MYSQL 查看最大连接数和修改最大连接数
查看>>
MySQL 查看有哪些表
查看>>
mysql 查看锁_阿里/美团/字节面试官必问的Mysql锁机制,你真的明白吗
查看>>
MySql 查询以逗号分隔的字符串的方法(正则)
查看>>
MySQL 查询优化:提速查询效率的13大秘籍(避免使用SELECT 、分页查询的优化、合理使用连接、子查询的优化)(上)
查看>>
mysql 查询数据库所有表的字段信息
查看>>
【Java基础】什么是面向对象?
查看>>
mysql 查询,正数降序排序,负数升序排序
查看>>