K.Os
K.Os

Reputation: 5506

Distinguish if zip one Single with other based on if statement

I am subscribing to two Singles which are zipped:

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

Now I want to distinguish which of the repositories I want to sync based on a Boolean. So I can make sync on only one repository or if they are both "enabled" perform this zipWith operator on them.

How can I do this in a clean way?

Upvotes: 0

Views: 113

Answers (1)

homerman
homerman

Reputation: 3579

you could:

  1. map the emission from each repository into another wrapper type that includes that boolean flag
  2. in the zip function evaluate the boolean flags to determine which repository's value emission to use

something like this:

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();

Upvotes: 1

Related Questions