我有一个抽象类,里面有一个MediatorLiveData对象。该对象有多个源,其中一个依赖于childs类,并且是父类中的abstract。在init块中添加源代码会在运行时导致NullPointerException,因为在init块添加源代码的时候,它仍然是抽象的(或者我被误认为是这样)。
有没有一种方法可以使用abstract LiveData作为MediatorLiveData的源,而不必在子类中设置该源?我只想override val并完成它,因为我肯定会忘记在将来的某个时候调用addSources()函数。
(我知道这个示例并不是做这件事的最有用的方法,但我不想增加不必要的复杂性)
示例:
abstract class MyClass: ViewModel(){
private val _myMediator = MediatorLiveData<String>()
protected abstract val mySource: LiveData<String>
val myObservable: LiveData<String>
get() = _myMediator
// This will cause a NullPointerException at runtime
init{
_myMediator.addSource(mySource){ _myMediator.value = it }
}
//This should work, but requires this to be called in child class
protected fun addSources(){
_myMediator.addSource(mySource){ _myMediator.value = it }
}
}
class myChild: MyClass(){
override val mySource = Transformations.map(myRepository.someData) { it.toString() }
// This is where init { addSources() } would be called
}在阅读了Stachu的回复后,我决定使用这个,我没有测试butI认为应该可以工作:
abstract class MyFixedClass: ViewModel(){
private val _myMediator: MediatorLiveData<String> by lazy{
MediatorLiveData<String>().apply{
addSource(mySource){ this.value = it }
}
}
protected abstract val mySource: LiveData<String>
val myObservable: LiveData<String>
get() = _myMediator
}
class MyChild: MyFixedClass(){
override val mySource = Transformations.map(myRepository.someData) { it.toString() }
}发布于 2020-10-01 21:17:33
使用惰性求值怎么样,比如下面这样
abstract class MyClass : ViewModel() {
private val _myMediator = MediatorLiveData<String>()
private val _mySource: LiveData<String> by lazy { mySource() }
protected abstract fun mySource(): LiveData<String>
val myObservable: LiveData<String>
get() = _myMediator
init {
_myMediator.addSource(_mySource) { _myMediator.value = it }
}
}
class myChild : MyClass() {
override fun mySource() = Transformations.map(myRepository.someData) { it.toString() }
}https://stackoverflow.com/questions/64152758
复制相似问题