如何将LiveData<List<Foo>>转换为LiveData<List<Bar>>?



假设我们有两个对象:

LiveData<List<Foo>> fooList;
LiveData<List<Bar>> barList;

,通过某些方法(或构造函数)可以转换为条对象。什么是转换第一个可观察的方法的最佳方法,该观察值将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,此示例应用程序演示了一个自定义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为您提供服务。

最新更新