How to update LiveData by set a value to variable

江枫思渺然 提交于 2021-01-29 14:07:18

问题


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")

回答1:


Use switchmap:

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

Then:

trigger.value = "value1"


来源:https://stackoverflow.com/questions/63898452/how-to-update-livedata-by-set-a-value-to-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!