Skip to content

Instantly share code, notes, and snippets.

@vorce
Created March 26, 2014 19:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vorce/9791756 to your computer and use it in GitHub Desktop.
Save vorce/9791756 to your computer and use it in GitHub Desktop.
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