假设我们有两个 LiveData 对象:
LiveData<List<Foo>> fooList;
LiveData<List<Bar>> barList;
并且通过某种方法(或构造函数)可以将 Foo 转换为 Bar 对象。
将第一个具有 Foo 对象列表的可观察对象转换为具有 Bar 对象列表的可观察对象的最佳方法是什么。
我知道可以这样做:
barList = Transformations.map(fooList, fooList1 -> {
List<Bar> barList = new ArrayList<>();
for (Foo foo: fooList1) {
barList.add(new Bar(foo));
}
return barList;
});
但是,是否有一种类似于 RxJava 中的 flatMap 运算符的更好方法,通过它我们可以动态地对列表中的项目进行所有必要的转换,而不是像上面的示例中那样处理列表本身?
您可以按照源中显示的配方创建自己的转换Transformations
. FWIW, 这个示例应用程序 https://github.com/commonsguy/cw-androidarch/tree/v0.2/General/LiveFilter演示了一个自定义filter()
执行:
/***
Copyright (c) 2017 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.
Covered in detail in the book _Android's Architecture Components_
https://commonsware.com/AndroidArch
*/
package com.commonsware.android.livedata;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MediatorLiveData;
import android.arch.lifecycle.Observer;
import android.support.annotation.MainThread;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
class LiveTransmogrifiers {
interface Confirmer<T> {
boolean test(T thingy);
}
@MainThread
static <X> LiveData<X> filter(@NonNull LiveData<X> source,
@NonNull final Confirmer<X> confirmer) {
final MediatorLiveData<X> result=new MediatorLiveData<>();
result.addSource(source, new Observer<X>() {
@Override
public void onChanged(@Nullable X x) {
if (confirmer.test(x)) {
result.setValue(x);
}
}
});
return(result);
}
}
否则,不行。LiveData
是一个具有生命周期感知能力的轻量级 RxJava 类似物。如果您需要大量运算符,那么直接使用 RxJava 会更好。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)