如何将MediatorLiveData与抽象源一起使用

时间:2020-10-01 09:41:12

标签: android kotlin abstract-class android-livedata mediatorlivedata

我有一个抽象类,其中有一个MediatorLiveData对象。该对象具有许多源,其中之一取决于子类,并且在父类中为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的答案后,我决定使用这个,虽然我没有测试,但是我认为应该可以:

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() }
}

1 个答案:

答案 0 :(得分:2)

如何使用惰性评估,例如像这样的东西

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() }
}