Reputation: 5506
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
Reputation: 3579
you could:
map
the emission from each repository into another wrapper type that includes that boolean flagzip
function evaluate the boolean flags to determine which repository's value emission to usesomething 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