Last active
September 7, 2016 20:59
-
-
Save ragdroid/f3697d4b37f99dc53fd7d319043ca264 to your computer and use it in GitHub Desktop.
Example of Rxjava retry and repeat operator - DroidconIN 2016
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
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; | |
} | |
} |
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
// 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