如何通过将值设置为变量来更新LiveData [英] How to update LiveData by set a value to variable

查看:384
本文介绍了如何通过将值设置为变量来更新LiveData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量和一个LiveData,我想在为该变量设置一个值时更新LiveData.

I have a variable and a LiveData, and I want to update the LiveData when I set a value to the variable.

var trigger = ""
val updateValue: LiveData<Value> = service.getValue(trigger)

// when set the value1 to trigger, the updateValue need to update the value.
var trigger = "value1"
val updateValue: LiveData<Value> = service.getValue("value1")

推荐答案

使用 switchmap :

var trigger = MutableLiveData<String>()
val updateValue: LiveData<Value> = Transformations.switchMap(trigger) {
        service.getValue(it)
}

然后:

trigger.value = "value1"

这篇关于如何通过将值设置为变量来更新LiveData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆