0

我正在做我的第一次实习,我正在一个项目中将 RX 代码转换为 LiveData。在某些时候,我不得不在某些存储库中用 observeForever() + Globalscope(Dispatchers.Main) 替换 subscribe() 函数,但显然使用 observeForever() 并不是最好的做法,我的实习导师建议我使用 Transformations.map () 反而 。

我不确定如何在以下代码(在存储库中)中使用 map() 而不是 observeForever:

        //I am using Globalscope with Dispathers.Main otherwise I get "cannot observeForever in a background Thread error
        GlobalScope.launch(Dispatchers.Main){
            someBooleanLiveData.observeForever { 
                if (it) {
                    // DO SOMETHING
                } else {
                    // DO SOMETHING ELSE
                }
            }
        }

我从 Transformations.map() 函数中了解到的是,它用于映射给定 LiveData 对象的值,就像ReactiveX的Map 运算符一样

我试过了,但似乎没有做我想做的事:

        Transformations.map(someBooleanLiveData){
            if (it) {
                // DO SOMETHING
            } else {
                // DO SOMETHING ELSE
            }
        }

我的问题是我应该如何使用 Transformation.map() 来避免 observeForever ?

做某事:如果你需要一个例子,可能是一个 livedataObject.postValue(it)

提前感谢您的回复。

4

1 回答 1

2

Transformations.map旨在用于转换观察到的每个元素。所以它没有一个有条件的方法来防止排放。举例:

Transformations.map(booleanLiveData) {
    if (it) 1 else 0
}

那返回一个LiveData<Int>

如果您想添加条件以使您的实时数据仅有时发出,那么您必须使用MediatorLiveData

class MyMediator : MediatorLiveData<SomeType>() {


    //we can create this wrapper method for convenience    
    fun addBooleanSource(booleanLiveData: LiveData<Boolean>) {
        //this method is already exposed and you can wrap it or do it in the invoker
        addSource(booleanLiveData) {
           if (it) {
                value = //do something
           }
        }
    }
     
}

诀窍是MediatorLiveData可以value作为字段访问,因此您可以选择何时更新它,何时不更新,还可以在此过程中应用转换。

为了以您需要的方式使用它:

        private val _myMediator = MyMediator()
        val myMediator: LiveData<YourType>
            get() = _myMediator

        GlobalScope.launch(Dispatchers.Main){
            _myMediator.addBooleanSource(someBooleanLiveData)
        }

然后观察myMediator

于 2021-05-11T14:42:23.990 回答