2016-09-02 42 views
0

我使用retrofit將REST API調用的結果返回給服務器。通常會發生請求超時異常,並且observable停止執行。如何重新訂閱重試,如果異常是一個特定類型的如果發生超時異常,則重新訂閱可觀察項

myObservable 
    .subscribe(new Subscriber<Something> sub(){ 
     @override 
     void onNext(Something something){ 
      //do something with something 
     } 
        @override 
     void onError(Throwable e){ 
      //retry and resend call to server if e is request timeout exception 
     } 

回答

2

可以使用retry運營商。

實施例:

myObservable 
    .retry((retryCount, throwable) -> retryCount < 3 && throwable instanceof SocketTimeoutException) 
    .subscribe(new Subscriber<Something> sub(){ 
     @override 
     void onNext(Something something){ 
      //do something with something 
     } 
        @override 
     void onError(Throwable e){ 

     } 

在該例子時,有一個最大SocketTimeoutException 3次,將重新訂閱。

或不拉姆達:

myObservable 
    .retry(new Func2<Integer, Throwable, Boolean>() { 
       @Override 
       public Boolean call(Integer retryCount, Throwable throwable) { 
        return retryCount < 3 && throwable instanceof SocketTimeoutException; 
       } 
      }) 
    .subscribe(new Subscriber<Something> sub(){ 
     @override 
     void onNext(Something something){ 
      //do something with something 
     } 
        @override 
     void onError(Throwable e){ 

     } 
+0

請使用語法,而不lambda表達式。我是編程新手,並不熟悉lambdas –

+0

@MuhammadArsal已更新 – LordRaydenMK

+0

這正是我想要實現的。也許你也可以幫我用這個 http://stackoverflow.com/questions/39309910/repeatedly-make-api-call-with-retrofit-and-rxjava –