博客
关于我
ViewModel LiveData 使用初体验
阅读量:347 次
发布时间: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/

你可能感兴趣的文章
输出10行杨辉三角——C语言
查看>>
浅析物联网无线(Bluetooth/Wi-Fi/Zigbee/Z-Wave/Cellular)通信协议
查看>>
【DFS】【暴力】KC看星(star)
查看>>
【最短路】【枚举】最短路(path)
查看>>
洛谷P7472 [NOI Online 2021 入门组] 吃豆人(民间数据)
查看>>
【DP】糖果盒
查看>>
【数论】小X的密码破译
查看>>
【贪心?】小X的AK计划
查看>>
【模拟】优美三角剖分
查看>>
【6.6】初一模拟赛
查看>>
2019暑假·纪中记Day1-Day3
查看>>
【普及模拟】交换
查看>>
【普及模拟】好数
查看>>
python调用netmiko库实现华为设备自动备份
查看>>
c语言扫雷游戏,可以递归展开非雷位置,第一次不踩雷
查看>>
C++STL容器----List
查看>>
4*4矩阵键盘的FPGA驱动
查看>>
SPI主机的Verilog代码及验证(优化版)
查看>>
椭圆曲线密码系统——椭圆曲线
查看>>
七 socket编程
查看>>