Skip to content

Instantly share code, notes, and snippets.

@vorce
Last active August 29, 2015 13:57
Show Gist options
  • Save vorce/9709863 to your computer and use it in GitHub Desktop.
Save vorce/9709863 to your computer and use it in GitHub Desktop.
Conditional Observable stuff
// First sketch, with just functions.
// Usage:
// Observable<Boolean> myCondition = ...
// Observable<List<Foo>> foos = onCondition(myCondition,
// fetchFoos(a1, a2, a3), // returns a Func0<Observable<List<Foo>>>
// { empty() })
// .flatMap({it})
public final static <R> Observable<R> onCondition(Observable<Boolean> observable,
final Func0<? extends R> onTrue,
final Func0<? extends R> onFalse) {
observable.map(conditionalFn(onTrue, onFalse))
}
static def <R> Func1<? super Boolean, ? extends R> conditionalFn(Func0<? extends R> onTrue, Func0<? extends R> onFalse) {
{ boolean condition ->
if(condition) {
onTrue()
} else {
onFalse()
}
}
}
public final static <R> Observable<R> onCondition(Observable<Boolean> observable, final Func0<? extends R> onTrue) {
observable.map(conditionalFn(onTrue))
}
static def <R> Func1<? super Boolean, ? extends R> conditionalFn(Func0<? extends R> onTrue) {
{ boolean condition ->
if(condition) {
onTrue()
}
}
}
// Second sketch with class instead
// Usage:
// Observable<Boolean> myCondition = ...
// Observable<List<Foo>> foos = new ConditionalObs<>(myCondition)
// .onTrue(fetchFoos(a1, a2, a3))
// .onFalse( { empty() })
// .build()
// .flatMap({it})
public class ConditionalObs<R> {
private final Observable<Boolean> condition
private Func0<? extends R> onTrue = {}
private Func0<? extends R> onFalse = {}
ConditionalObs(Observable<Boolean> condition) {
this.condition = condition
}
public ConditionalObs onTrue(final Func0<? extends R> onTrue) {
this.onTrue = onTrue
this
}
public ConditionalObs onFalse(final Func0<? extends R> onFalse) {
this.onFalse = onFalse
this
}
public Observable<R> build() {
condition.map(conditionalFn(onTrue, onFalse))
}
private Func1<? super Boolean, ? extends R> conditionalFn(Func0<? extends R> onTrue, Func0<? extends R> onFalse) {
{ boolean condition ->
if(condition) {
onTrue()
} else {
onFalse()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment