Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ragdroid
Last active September 7, 2016 20:59
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 ragdroid/f3697d4b37f99dc53fd7d319043ca264 to your computer and use it in GitHub Desktop.
Save ragdroid/f3697d4b37f99dc53fd7d319043ca264 to your computer and use it in GitHub Desktop.
Example of Rxjava retry and repeat operator - DroidconIN 2016
private class Boggart {
private static final int MAX_LAUGHTER_LEVEL = 10;
private static final int MIN_LAUNGHTER_LEVEL = 0;
private static final int LAUGHTER_FUNNY_THRESHOLD = 5;
private static final int LAUGHTER_HILARIOUS_THRESH = 7;
private int laughterLevel;
public Boggart() {
init();
}
public void init() {
this.laughterLevel = MIN_LAUNGHTER_LEVEL;
}
public void riddikulus() {
int level = new Random().nextInt(MAX_LAUGHTER_LEVEL);
this.laughterLevel = level;
}
public boolean isFunny() {
return this.laughterLevel > LAUGHTER_FUNNY_THRESHOLD;
}
public boolean isHilarious() {
return isFunny() && this.laughterLevel > LAUGHTER_HILARIOUS_THRESH;
}
}
// Example of repeat and retry
private Observable<Boggart> riddikulus() {
return getBoggartObservable()
.flatMap(new Func1<Boggart, Observable<Boggart>>() {
@Override
public Observable<Boggart> call(Boggart boggart) {
boggart.init();
boggart.riddikulus();
if (boggart.isFunny()) {
return Observable.just(boggart);
}
return Observable.error(new BoggartException());
}
})
.retry()
.repeat(10) // repeat 10 times
.takeUntil(new Func1<Boggart, Boolean>() { // take until Boggart is not Hilarious
@Override
public Boolean call(Boggart boggart) {
return boggart.isHilarious();
}
}).filter(new Func1<Boggart, Boolean>() { // filter the input to only get the final Hilarious event
@Override
public Boolean call(Boggart boggart) {
return boggart.isHilarious();
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment