博客
关于我
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-Explain的详解
查看>>
mysql-group_concat
查看>>
MySQL-redo日志
查看>>
MySQL-【1】配置
查看>>
MySQL-【4】基本操作
查看>>
Mysql-丢失更新
查看>>
Mysql-事务阻塞
查看>>
Mysql-存储引擎
查看>>
mysql-开启慢查询&所有操作记录日志
查看>>
MySQL-数据目录
查看>>
MySQL-数据页的结构
查看>>
MySQL-架构篇
查看>>
MySQL-索引的分类(聚簇索引、二级索引、联合索引)
查看>>
Mysql-触发器及创建触发器失败原因
查看>>
MySQL-连接
查看>>
mysql-递归查询(二)
查看>>
MySQL5.1安装
查看>>
mysql5.5和5.6版本间的坑
查看>>
mysql5.5最简安装教程
查看>>
mysql5.6 TIME,DATETIME,TIMESTAMP
查看>>