Created
March 26, 2014 19:53
-
-
Save vorce/9791756 to your computer and use it in GitHub Desktop.
ObservableCondition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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