博客
关于我
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中datetime与timestamp类型有什么区别
查看>>
MySQL中DQL语言的执行顺序
查看>>
mysql中floor函数的作用是什么?
查看>>
MySQL中group by 与 order by 一起使用排序问题
查看>>
mysql中having的用法
查看>>
MySQL中interactive_timeout和wait_timeout的区别
查看>>
mysql中int、bigint、smallint 和 tinyint的区别、char和varchar的区别详细介绍
查看>>
mysql中json_extract的使用方法
查看>>
mysql中json_extract的使用方法
查看>>
mysql中kill掉所有锁表的进程
查看>>
mysql中like % %模糊查询
查看>>
MySql中mvcc学习记录
查看>>
mysql中null和空字符串的区别与问题!
查看>>