RxJava Retrywhen operator implements error retry mechanism

Source: Internet
Author: User
Tags throwable

Business requirements

When we launch a network request in the app, it may cause a failure due to various problems. How to use Rxjava to retry several times after an error occurs, and to set the time interval for retries.

Specific implementation

Network requests to use retrofit, or use 请求用户信息接口 the

    @GET("/userinfo?noToken=1")    Observable<Response> getUserInfoNoToken();

The following is 请求用户信息接口 the logical code

Userapi.getuserinfonotoken ()//3 retries in total, 3000 milliseconds retry interval. Retrywhen (NewRetrywithdelay (3, the). Observeon (Androidschedulers.mainthread ()). Subscribeon (Schedulers.io ()) . Subscribe (NewAction1<response> () {@Override                             Public void Pager(Response Response) {String content =NewString ((Typedbytearray) response.getbody ()). GetBytes ()); Printlog (Tvlogs,"", content); }                        },NewAction1<throwable> () {@Override                             Public void Pager(Throwable throwable)                            {Throwable.printstacktrace (); }                        });

RetryWithDelay

Public    class retrywithdelay implementsFunc1<  Observable<? extends throwable, Observable<?>             > {private final int maxretries;        private final int retrydelaymillis;        private int retrycount;            Public retrywithdelay (int maxretries, int retrydelaymillis) {this.maxretries = maxretries;        This.retrydelaymillis = Retrydelaymillis; } @Override Public Observable <?> Call (Observable<? extends throwable> attempts) {return attempts. FlatMap (new func1< ; Throwable, Observable<? >            > () {@Override public Observable<?> Call (Throwable throwable) {if(++retrycount <= maxretries) {//When this Observable calls OnNext, the original Observable would be retried (i.e. re-subscribed).Printlog (Tvlogs,"","Get error, it'll try after"+ Retrydelaymillis +"millisecond, retry count"+ RetryCount);returnObservable.timer (Retrydelaymillis, timeunit.milliseconds); }//Max retries hit. Just pass the error along.                            returnObservable.error (Throwable);        }                    }); }    }

How do I simulate retries?

Method One: Shut down the server, after shutting down the server, the client requests the interface will inevitably error, see if it is retried three times.

Run output:

‘Get Error,itWouldTry  After  theMillisecond, retryCount 1' Main Thread:false, Thread Name:retrofit-idle 'Get Error,itWouldTry  After  theMillisecond, retryCount 2' Main Thread:false, Thread Name:retrofit-idle 'Get Error,itWouldTry  After  theMillisecond, retryCount 3' Main Thread:false, Thread Name:retrofit-idle

It was retried three times, but how do we know if the request succeeds in the next retry after the server starts? Next try Method two.

Method Two: Turn off the server first, and when you click on the button request, start the Tomcat server.

Run output:

 "get  error , it  would try  after  3000  millisecond, retry count  1  ' Main thread:false , Thread name:retrofit-idle ' get  error , it  Would try  after  3000  millisecond, retry count  2  ' Main thread:< Span class= "Hljs-constant" >false , Thread name:retrofit-idle ' username:chiclaim,age: 007  ' Main thread:true , Thread name:main 

It can be found that the server is available at the third retry.

GitHub Source Download

RxJava Retrywhen operator implements error retry mechanism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.