Skip to content

Instantly share code, notes, and snippets.

@vorce
Created Mar 26, 2014
Embed
What would you like to do?
ObservableCondition
/**
* Observes an {@link Observable<T>} and returns a new Observable<R> that emits
* items based on the predicate<T> and the <R> onTrue and <R> onFalse functions.
*/
public class ObservableCondition<R, T> {
private final rx.Observable<T> condition;
private Func0<? extends R> onTrue = {}
private Func0<? extends R> onFalse = {}
private Predicate<T> predicate;
private def ofBoolean = new Predicate<Boolean>() {
@Override
boolean apply(Boolean inp) {
inp.booleanValue()
}
}
ObservableCondition(rx.Observable<T> condition) {
this.condition = condition
this.predicate = ofBoolean
}
ObservableCondition(rx.Observable<T> condition, Predicate<T> predicate) {
this.condition = condition
this.predicate = predicate
}
public ObservableCondition onTrue(final Func0<? extends R> onTrue) {
this.onTrue = onTrue
this
}
public ObservableCondition onFalse(final Func0<? extends R> onFalse) {
this.onFalse = onFalse
this
}
public ObservableCondition predicate(Predicate<?> predicate) {
this.predicate = predicate
this
}
public rx.Observable<R> build() {
condition.map(predicateFn(predicate, onTrue, onFalse))
}
private static <T> Func1<T, ? extends R> predicateFn(Predicate<T> predicate,
Func0<? extends R> onTrue,
Func0<? extends R> onFalse) {
{ T inp ->
if(predicate.apply(inp)) {
onTrue()
} else {
onFalse()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment