根据if语句将一个Single与另一个分开

时间:2018-08-29 13:11:43

标签: kotlin rx-java2

我要订阅两个压缩的单打:

 firstRepository.sync(id)
      .zipWith(secondRepository.sync(id))

现在,我想基于布尔值来区分要同步的存储库。因此,我只能在一个存储库上进行同步,或者如果它们都已“启用”,则对它们执行此zipWith运算符。

我如何以一种干净的方式做到这一点?

1 个答案:

答案 0 :(得分:1)

您可以:

  1. map从每个存储库到另一个包含该布尔标志的包装器类型的发射
  2. zip函数中,评估布尔值标志以确定要使用哪个存储库的值发射

类似这样的东西:

class Repository {
  Single<Integer> sync(String id) {
    return Single.just(Integer.valueOf(id));
  }
}

class State {
  final int value;
  final boolean active;

  State(int value, boolean active) {
    this.value = value;
    this.active = active;
  }
}

final Repository firstRepository = new Repository();
final Repository secondRepository = new Repository();

final Single<State> firstEmission =
    firstRepository
        .sync(...)
        .map(value -> new State(value, true)); // <-- boolean for firstRepository

final Single<State> secondEmission =
    secondRepository
        .sync(...)
        .map(value -> new State(value, false)); // <-- boolean for secondRepository

firstEmission.zipWith(secondEmission, (first, second) -> {
  if(first.active && !second.active) {
    // firstRepository is active so use its emission...
    return first.value;

  } else if(!first.active && second.active) {
    // secondRepository is active so use its emission...
    return second.value;

  } else if(first.active && second.active) {
    // both repositories are active, so apply some special logic...
    return first.value + second.value;

  } else {
    throw new RuntimeException("No active repository!");
  }
})
    .subscribe();