Created
November 22, 2016 20:15
-
-
Save jankowskib/b2d057f577011e461a8f371afd1e6e2e to your computer and use it in GitHub Desktop.
retry when receive specific error
This file contains hidden or 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
package com.example; | |
import java.io.IOException; | |
import java.lang.invoke.WrongMethodTypeException; | |
import java.util.concurrent.TimeUnit; | |
import rx.Emitter; | |
import rx.Observable; | |
import rx.schedulers.Schedulers; | |
public class MyClass { | |
static boolean shouldPass = false; | |
static boolean boromirWarn = true; | |
public static class Pair<T1, T2> { | |
T1 first; | |
T2 second; | |
public Pair(T1 first, T2 second) { | |
this.first = first; | |
this.second = second; | |
} | |
} | |
public static void main(String[] args){ | |
Observable.timer(2, TimeUnit.SECONDS).subscribe(delay -> { | |
System.out.println("Gandalf: You shall now pass"); | |
shouldPass = true; | |
}); | |
Observable<String> walkIntoMordor = Observable.fromEmitter(e -> | |
{ | |
System.out.println("I want to walk into Mordor!"); | |
if(!shouldPass) { | |
e.onError(new IOException("Gandalf: You shall not pass")); | |
return; | |
} | |
if(boromirWarn) { | |
e.onError(new WrongMethodTypeException("Boromir: One Does Not Simply Walk into Mordor")); | |
return; | |
} | |
e.onNext("Mordor!"); | |
e.onCompleted(); | |
}, Emitter.BackpressureMode.NONE); | |
walkIntoMordor.retryWhen(e -> e | |
.zipWith(Observable.interval(500, TimeUnit.MILLISECONDS), (err, i) -> new Pair<>(err, i)) | |
.flatMap(k -> { | |
if(k.second == 5) | |
return Observable.error(k.first); | |
if(k.first instanceof IOException) { | |
System.out.println("Waiting for Gandalf"); | |
return Observable.just(null); | |
} | |
System.out.println("Boromir should warn you"); | |
return Observable.error(k.first); | |
}) | |
) | |
.observeOn(Schedulers.newThread()) | |
.subscribeOn(Schedulers.computation()) | |
.toBlocking() | |
.subscribe(msg -> | |
System.out.println("And i passed : " + msg) | |
, e -> System.out.println("You won't never pass: " + e.getMessage()) | |
, () -> System.out.println("I am on my destination!")); | |
} | |
} | |
/* | |
.flatMap(k -> { | |
if(k.second == 5) | |
return Observable.error(k.first); | |
if(k.first instanceof IOException) { | |
System.out.println("Waiting for Gandalf"); | |
return Observable.just(null); | |
} | |
System.out.println("Boromir should warn you"); | |
return Observable.error(k.first); | |
}) | |
) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment