首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在抽象源代码中使用MediatorLiveData

如何在抽象源代码中使用MediatorLiveData
EN

Stack Overflow用户
提问于 2020-10-01 17:41:12
回答 1查看 66关注 0票数 0

我有一个抽象类,里面有一个MediatorLiveData对象。该对象有多个源,其中一个依赖于childs类,并且是父类中的abstract。在init块中添加源代码会在运行时导致NullPointerException,因为在init块添加源代码的时候,它仍然是抽象的(或者我被误认为是这样)。

有没有一种方法可以使用abstract LiveData作为MediatorLiveData的源,而不必在子类中设置该源?我只想override val并完成它,因为我肯定会忘记在将来的某个时候调用addSources()函数。

(我知道这个示例并不是做这件事的最有用的方法,但我不想增加不必要的复杂性)

示例:

代码语言:javascript
复制
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认为应该可以工作:

代码语言:javascript
复制
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() }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-01 21:17:33

使用惰性求值怎么样,比如下面这样

代码语言:javascript
复制
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() }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64152758

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档