Search code examples
javaandroidrx-javareactive-programmingreactivex

Resubscribing an observable if timeout exception occurs


i'm using retrofit to return an observable as a result of REST API call to server. Its very usual that a request timeout exception occurs and observable stops executing. How to resubscribe of retry if exception is of a specific type

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
        }

Solution

  • You can use the retry operator.

    Example:

    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){
    
            }
    

    In the example it will resubscribe when there is a SocketTimeoutException max 3 times.

    or without lambda:

    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){
    
            }