具有多个参数的MediatorLiveData或switchMap转换

时间:2018-03-26 14:23:38

标签: android observer-pattern android-architecture-components android-livedata android-viewmodel

我在我的ViewModel中使用Transformations.switchMap,因此我的片段中观察到的LiveData集合会对code参数的更改做出反应。

这非常有效:

public class MyViewModel extends AndroidViewModel {

    private final LiveData<DayPrices> dayPrices;
    private final MutableLiveData<String> code = new MutableLiveData<>();
    // private final MutableLiveData<Integer> nbDays = new MutableLiveData<>();
    private final DBManager dbManager;

    public MyViewModel(Application application) {
        super(application);
        dbManager = new DBManager(application.getApplicationContext());
        dayPrices = Transformations.switchMap(
            code,
            value -> dbManager.getDayPriceData(value/*, nbDays*/)
        );
    }

    public LiveData<DayPrices> getDayPrices() {
        return dayPrices;
    }

    public void setCode(String code) {
        this.code.setValue(code);
    }

    /*public void setNbDays(int nbDays) {
        this.nbDays.setValue(nbDays);
    }*/

}

public class MyFragment extends Fragment {

    private MyViewModel myViewModel;

    myViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
    myViewModel.setCode("SO");
    //myViewModel.setNbDays(30);
    myViewModel.getDayPrices().observe(MyFragment.this, dataList -> {
        // update UI with data from dataList
    });
}

问题

我现在需要另一个参数(nbDays在上面的代码中注释),以便我的LiveData对象对两个参数的变化做出反应(codenbDays)。< / p>

如何链接转换?

有些读数指向MediatorLiveData,但它没有解决我的问题(仍然需要调用带有2个参数的单个DB函数,我不需要合并2个liveDatas)。

所以我尝试了这个而不是switchMap,但codenbDays始终为空。

dayPrices.addSource(
    dbManager.getDayPriceData(code.getValue(), nbDays.getValue),
    apiResponse -> dayPrices.setValue(apiResponse)
);

一种解决方案是将对象作为单个参数传递,我非常确定有一个简单的解决方案。

4 个答案:

答案 0 :(得分:21)

来源:https://plus.google.com/+MichielPijnackerHordijk/posts/QGXF9gRomVi

要为someOptional.isPresent()设置多个触发器,您需要使用自定义switchMap()来观察LiveData对象的组合 -

MediatorLiveData

然后你可以这样做 -

class CustomLiveData extends MediatorLiveData<Pair<String, Integer>> {
    public CustomLiveData(LiveData<String> code, LiveData<Integer> nbDays) {
        addSource(code, new Observer<String>() {
            public void onChanged(@Nullable String first) {
                setValue(Pair.create(first, nbDays.getValue()));
            }
        });
        addSource(nbDays, new Observer<Integer>() {
            public void onChanged(@Nullable Integer second) {
                setValue(Pair.create(code.getValue(), second));
            }
        });
    }
}

如果您使用Kotlin并希望使用泛型:

CustomLiveData trigger = new CustomLiveData(code, nbDays);
LiveData<DayPrices> dayPrices = Transformations.switchMap(trigger, 
    value -> dbManager.getDayPriceData(value.first, value.second));

然后:

class DoubleTrigger<A, B>(a: LiveData<A>, b: LiveData<B>) : MediatorLiveData<Pair<A?, B?>>() {
    init {
        addSource(a) { value = it to b.value }
        addSource(b) { value = a.value to it }
    }
}

答案 1 :(得分:11)

简化jL4的答案(在Kotlin中以防万一,也可以帮助任何人)...无需为此创建自定义类:

class YourViewModel: ViewModel() {

    val firstLiveData: LiveData<String> // or whatever type
    val secondLiveData: LiveData<Int> // or whatever

    // the Pair values are nullable as getting "liveData.value" can be null
    val combinedValues = MediatorLiveData<Pair<String?, Int?>>().apply {
        addSource(firstLiveData) { 
           value = Pair(it, secondLiveData.value)
        }
        addSource(secondLiveData) { 
           value = Pair(firstLiveData.value, it)
        }
    }

    val results = Transformations.switchMap(combinedValues) { pair ->
      val firstValue = pair.first
      val secondValue = pair.second
      if (firstValue != null && secondValue != null) {
         yourDataSource.yourLiveDataCall(firstValue, secondValue)
      } else null
    }

}

说明

firstLiveDatasecondLiveData中进行的任何更新都会更新combinedValues的值,并将两个值成对发出(这要感谢jL4)。

调用liveData.value可以为null,因此此解决方案使Pair中的值可以为null,以避免Null Pointer Exception。

因此,对于实际结果/数据源调用,切换映射位于combinedValues实时数据上,并且从Pair中提取了2个值并执行了空检查,因此可以确定将非空值传递到数据源的过程。

答案 2 :(得分:6)

@ jL4提出的自定义MediatorLiveData效果很好,可能就是解决方案。

我只想分享最简单的解决方案,我认为使用内部类来表示合成的过滤器值:

public class MyViewModel extends AndroidViewModel {

    private final LiveData<DayPrices> dayPrices;
    private final DBManager dbManager;
    private final MutableLiveData<DayPriceFilter> dayPriceFilter;

    public MyViewModel(Application application) {
        super(application);
        dbManager = new DBManager(application.getApplicationContext());
        dayPriceFilter = new MutableLiveData<>();
        dayPrices = Transformations.switchMap(dayPriceFilter, input -> dbManager.getDayPriceData(input.code, input.nbDays));
    }

    public LiveData<DayPrices> getDayPrices() {
        return dayPrices;
    }

    public void setDayPriceFilter(String code, int nbDays) {
        DayPriceFilter update = new DayPriceFilter(code, nbDays);
        if (Objects.equals(dayPriceFilter.getValue(), update)) {
            return;
        }
        dayPriceFilter.setValue(update);
    }

    static class DayPriceFilter {
        final String code;
        final int nbDays;

        DayPriceFilter(String code, int nbDays) {
            this.code = code == null ? null : code.trim();
            this.nbDays = nbDays;
        }
    }

}

然后在activity / fragment中:

public class MyFragment extends Fragment {

    private MyViewModel myViewModel;

    myViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
    myViewModel.setDayPriceFilter("SO", 365);
    myViewModel.getDayPrices().observe(MyFragment.this, dataList -> {
        // update UI with data from dataList
    });
}

答案 3 :(得分:0)

我遇到了类似的问题。有两种方法可以解决这个问题:

  1. 使用MediatorLiveData
  2. 使用RxJava,因为它有各种运算符来做这种复杂的东西
  3. 如果您不了解RxJava,那么我建议您编写自定义MediatorLiveData课程。 要了解如何编写自定义<video id="v" controls autoplay> <source src="file:///D:/---/New/Replay%202018-03-27%2016-35-57.mp4" type="video/mp4"> </video> 类,请查看此示例: https://gist.github.com/AkshayChordiya/a79bfcc422fd27d52b15cdafc55eac6b