问题
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