【发布时间】:2019-01-19 13:04:14
【问题描述】:
MediatorLiveData 有问题。我想在不是 ViewModel 的类中从数据库中获取数据。我想指出下载数据的方法在 ViewModel 中有效,但是当我想在其他类中调用它时它不起作用。这是一个代码:
class MyReceiver: BroadcastReceiver() {
@Inject
lateinit var jobsRepository: jobsRepository
private val _jobStatusDone = MediatorLiveData<Boolean>()
val jobStatusDone: LiveData<Boolean>
get() = _jobStatusDone
private val _counterparties = MediatorLiveData<List<Counterparty>>()
override fun onReceive(context: Context?, intent: Intent?) {
AndroidInjection.inject(this, context)
val source = jobsRepository.getFulljobs()
_jobStatusDone.addSource(source) {
System.out.println("IT NEVER REACHES THIS PLACE.")
}
}
}
}
这很有趣,因为更新/插入有效。
编辑:我想指出我在此处发布的代码,适用于 ViewModel 的类。
【问题讨论】:
-
这条线肯定会阻塞
val source = jobsRepository.getFulljobs(),所以一旦你“观察” - (addSource(source)),变化已经发生,所以OnChanged不会被调用。从未使用过LiveData,所以我可能是错的。
标签: android kotlin android-livedata