Jetpack系列:LiveData入门级使用方法

框架搭建

APP首先需要搭建使用LiveData的环境:

  1. 导入依赖包
    //app build.gradle
    dependencies {

    implementation deps.lifecycle.viewmodel_ktx
    implementation deps.lifecycle.livedata_ktx

    }

  2. 创建ViewModel类(用于LiveData数据的封装,和UI交互)

class LiveDataViewModel(
private val dataSource: DataSource
) : ViewModel() {…}

  1. 布局文件中引用ViewModel对象





  2. Activity绑定ViewModel

//MainActivity
//成员变量
private val viewmodel: LiveDataViewModel by viewModels { LiveDataVMFactory }
//onCreate
val binding = DataBindingUtil.setContentView(
this, R.layout.activity_livedata
)
// Set the LifecycleOwner to be able to observe LiveData objects
binding.lifecycleOwner = this

// Bind ViewModel
binding.viewmodel = viewmodel
//LifeDataVMFactory
object LiveDataVMFactory : ViewModelProvider.Factory {
private val dataSource = DefaultDataSource(Dispatchers.IO)
override fun <T : ViewModel?> create(modelClass: Class): T {
@Suppress(“UNCHECKED_CAST”)
return LiveDataViewModel(dataSource) as T
}
}

注意:此处构造ViewModel采用的dataSource为DefaultDataSource,后续数据是根据此数据源来进行获取的。

系统时间(Long型)显示

系统时间的显示,通过在UI上绑定ViewModel,通过getCurrentTime方法后台更新、提交数据,来通知UI进行显示的更新。

//xml
<TextView
android:id="@+id/time"
android:text="@{Long.toString(viewmodel.currentTime)}"
…/>
//LiveDataViewModel
val currentTime = dataSource.getCurrentTime()
//DefaultDataSource
override fun getCurrentTime(): LiveData =
liveData {
while (true) {
emit(System.currentTimeMillis())//通知当前系统时间
delay(1000)//延时1秒
}
}

系统时间显示

系统时间的显示是根据系统获取的Long型变量变化映射得到的,Long值发生变化时,实时更新系统时间显示。

//xml
<TextView
android:id="@+id/time_transformed"
android:text="@{viewmodel.currentTimeTransformed}"
…/>
//LiveDataViewModel 此处有两种方式实现
//1. currentTime变更后实时通知UI更新
val currentTimeTransformed : LiveData = Transformations.map(currentTime) {
Date(it).toString()
}
//2. 延时500ms后通知
val currentTimeTransformed = currentTime.switchMap {
// timeStampToTime is a suspend function so we need to call it from a coroutine.
liveData { emit(timeStampToTime(it)) }
}
private suspend fun timeStampToTime(timestamp: Long): String {
delay(500) // Simulate long operation
val date = Date(timestamp)
return date.toString()
}

天气显示

天气的显示通过动态改变数据源提供的数据,从而通知UI显示(DataSource数据的更新实时通过LiveData传递到UI)。

//xml
<TextView
android:id="@+id/current_weather"
android:text="@{viewmodel.currentWeather}"
…/>
//LiveDataViewModel
val currentWeather: LiveData = liveData {
emit(LOADING_STRING)
emitSource(dataSource.fetchWeather())
}
//DefaultDataSource
private val weatherConditions = listOf(“Sunny”, “Cloudy”, “Rainy”, “Stormy”, “Snowy”)
override fun fetchWeather(): LiveData = liveData {
var counter = 0
while (true) {
counter++
delay(2000)//延时两秒
//按顺序循环显示weatherConditions中的天气数据信息
emit(weatherConditions[counter % weatherConditions.size])
}
}

远端数据显示

远端数据的请求通过Button的点击事件触发,数据获取成功后,通知TextView进行数据显示。

//xml
<TextView
android:id="@+id/cached_value"
android:text="@{viewmodel.cachedValue}"
…/>
<Button
android:id="@+id/refresh_button"
android:onClick="@{() -> viewmodel.onRefresh()}"
…/>
//LiveDataViewModel
val cachedValue = dataSource.cachedData
fun onRefresh() {
// Launch a coroutine that reads from a remote data source and updates cache
viewModelScope.launch {
dataSource.fetchNewData()
}
}
//DefaultDataSource
private val _cachedData = MutableLiveData(“This is old data”)
override val cachedData: LiveData = _cachedData
override suspend fun fetchNewData() {
// Force Main thread
withContext(Dispatchers.Main) {
_cachedData.value = “Fetching new data…”
_cachedData.value = simulateNetworkDataFetch()
}
}
private var counter = 0
// Using ioDispatcher because the function simulates a long and expensive operation.
private suspend fun simulateNetworkDataFetch(): String = withContext(ioDispatcher) {
delay(3000)//延时3秒
counter++
“New data from request #$counter”//返回此字符串
}
深圳网站建设www.sz886.com

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值