Retrofit+rxjava Brief Introduction

Source: Internet
Author: User
Tags getmessage set time time 0

Retrofit is a very popular network request library now.

Want to use it first reference in the Gradle file

Compile ' com.squareup.retrofit2:retrofit:2.1.0  ' com.squareup.retrofit2:adapter-rxjava:2.1.0 '    compile ' com.squareup.retrofit2:converter-gson:2.0.2 '

RxJava is an asynchronous responsive programming library for Java voice

Compile ' io.reactivex.rxjava2:rxjava:2.0.1 ' compile ' io.reactivex.rxjava2:rxandroid:2.0.1 '

Use of Retrofit

Create a Retrofit Object

Private Static void Initretrofit () {        new  retrofit.builder ()                . BASEURL ("http://www.weather.com.cn/" )                . Client (sokhttpclient).                addcalladapterfactory (Rxjavacalladapterfactory.create ())                . Addconverterfactory (Gsonconverterfactory.create ())                . Build ();    }

Client settings okhttp for interceptor settings

Addcalladapterfactory () setting supports Rxjava return value of oservable<m>

Addconverterfactory () setting supports Gson directly returning entity classes

Next, you create a Okhttpclient.buildr object

  

New Okhttpclient.builder ();

1 setting result interceptors

Interceptor Cacheinterceptor =NewInterceptor () {@Override PublicResponse Intercept (Chain Chain)throwsIOException {Request Request=chain.request (); if(!commonutil.isnetworkconnected (Myapplication.getinstance ())) {Request=Request.newbuilder (). CacheControl (Cachecontrol.force_cache). b                Uild (); } Response Response=chain.proceed (Request); Response.builder Newbuilder=Response.newbuilder (); if(commonutil.isnetworkconnected (Myapplication.getinstance ())) {intMaxAge = 0; //Set Cache timeout time 0 hours when there is a networkNewbuilder.header ("Cache-control", "public, max-age=" +MaxAge); } Else {                    //set timeout to 4 weeks when no network                    intMaxstale = 60 * 60 * 24 * 28; Newbuilder.header ("Cache-control", "Public, only-if-cached, max-stale=" +Maxstale); }                returnNewbuilder.build (); }        };

Here's a network to get the latest, no web cache

Add to Builder;

2. Set up the request blocker

Interceptor Requestinterceptor =NewInterceptor () {@Override PublicResponse Intercept (Chain Chain)throwsIOException {Request Request=chain.request (). Newbuilder (). AddHeader ("Accept", "Application/vnd.yu.v4+json"). AddHeader ("Content-type", "Application/json"). AddHeader ("Range", "Page:1,max:10"). AddHeader ("Authorization", "" "). Build (); Request.headers (). toString ()); returnchain.proceed (Request); }        };

Commonly used when unified header is set

Builder.addnetworkinterceptor (Requestinterceptor);

Set time-out to re-connect

Builder.connecttimeout (timeunit.seconds), Builder.readtimeout (timeunit.seconds); Builder.writetimeout (timeunit.seconds); Builder.retryonconnectionfailure (true);
return Builder.build ();

Okhttp Setup is complete.

Next go to set Apicallback

Using Rxjava Subscriptions

Apicallback<m> is abstract to inherit subscriber<m>

 Public Abstract classApicallback<m>extendsSubscriber<m> {     Public Abstract voidonsuccess (M model);  Public Abstract voidonfailure (String msg);  Public Abstract voidonfinish (); @Override Public voidOnError (Throwable e) {e.printstacktrace (); if(EinstanceofHttpException) {HttpException HttpException=(HttpException) e; intCode =Httpexception.code (); String msg=Httpexception.getmessage (); if(Code = = 504) {msg= "Network does not give force"; }            if(Code = = 502 | | code = = 404) {msg= "Server exception, please try again later";        } onfailure (msg); } Else{onfailure (E.getmessage ());    } onfinish (); } @Override Public voidOnNext (M model) {onsuccess (model); } @Override Public voidoncompleted () {onfinish (); }}

Next, write Apiservice.

Apiservice is an interface.

Retrofit the request method provided by the annotation to modify the variable generated URL, etc.

Rxjava Way

@GET ("adat/sk/{cityid}.html") Observable<MainModel> Getmainbanner (@Path ("Cityid") String Cityid ); // Request Way @get, @POST, @PUT @DELETE, etc. (@Path ("Cityid") String Cityid)    //modify the corresponding variable in the path {Cityid}@POSTObservable<MainModel>  Gettasktoken (@Url string Url, @Body string Body), @Headers ({"Accept:application/json", "content-type:application /json "}) @GETObservable<RecordsTask> getmaintask (@Url string Url, @Header (" Authorization ") string token);

The above is simple to write a few of the most include

What you need is already configured, so use it below.

  

// Rxjava Registration     Public void addsubscription (Observable Observable, subscriber subscriber) {        ifnull) {             New  compositesubscription ();        }        Mcompositesubscription.add (Observable                . Subscribeon (Schedulers.io ())                . Observeon ( Androidschedulers.mainthread ())                . Subscribe (subscriber));    }

Write the contents of the above in base

Subscribeon (): Specify

Subscribe() The thread that occurs when Observable.onsubscribe is activated. Or an event-generated thread.

Observeon(): Specifies the thread that the user is running. Or a thread called event consumption.

Use the Subscribeon () and Observeon () two methods to control the thread.

called in Activity

 Public voidLoadweather (String city) {addsubscription (Mapiservice.getmainbanner),NewApicallback<mainmodel>() {@Override Public voidonsuccess (Mainmodel response) {mmvpview.onsuccess (response); } @Override Public voidonfailure (String msg) {mmvpview.onfail (msg,1); } @Override Public voidonfinish () {}}); }

At the end, you also need to cancel Rxjava registration to avoid memory leaks

 Public void Onunsubscribe () {        ifnull && mcompositesubscription.hassubscriptions ()) {            mcompositesubscription.unsubscribe ();        }    }

End.

Retrofit+rxjava Brief Introduction

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.