我有两个 livedatas startedAt
&finishedAt
并希望在依赖于这两个值的转换中使用它们...我尝试使用 mediatorliveData 组合它们
fun <A, B> LiveData<A>.combine(other: LiveData<B>): PairLiveData<A, B> {
return PairLiveData(this, other)
}
class PairLiveData<A, B>(first: LiveData<A>, second: LiveData<B>) : MediatorLiveData<Pair<A?, B?>>() {
init {
addSource(first) { value = it to second.value }
addSource(second) { value = first.value to it }
}
}
并观察他们
val automaticActivities = Transformations.map(startedAt.combine(finishedAt)) {
Log.v("checkindex",index.toString()+" "+it.first?.size+" "+it.second?.size)
}
但这并没有按预期工作,因为 finishedAt 在获得所需值之前返回 null ,
调试结果:
V/检查索引:0 1 空
V/检查索引:0 1 1
在转换中使用转换是个好主意吗?前任:
val automaticActivities = Transformations.map(startedAt) {
val finishedAt = Transformations.map(finishedAt){
}
}