Rxjava+retrofit Implementing Network requests:
The first step is to add a dependency
Compile ' io.reactivex:rxjava:x.y.z ' io.reactivex:rxandroid:1.0.1 ' com.squareup.retrofit2:retrofit:2.0.2 ' com.squareup.retrofit2:converter-gson:2.0.2 ' ' com.squareup.retrofit2:adapter-rxjava:2.0.2 '
1. Create a network interface for retrofit requests
Public Interface Retrofitapi { // login @FormUrlEncoded @POST (constant.login) Observable<Responseinfo<LoginBean>> Setlogin (@Field ("mobile") String phone, @Field ("pwd") String pwd); // Register @FormUrlEncoded @POST (constant.registe) Observableint channel);}
2. Creating objects for retrofit and Rxjava
Public classRetrofithelper {//Set the default time-out for network requests Private Static Final intDefault_time_out = 10; Private StaticRetrofit Sretrofit; Private Staticokhttpclient sokhttpclient; Public StaticRetrofitapi Getretrofitapi () {returnGetInstance (). Create (Retrofitapi.class); } Public StaticRetrofit getinstance () {if(sretrofit==NULL){ synchronized(Retrofithelper.class){ if(Sretrofit = =NULL) {Sretrofit=NewRetrofit.builder (). BASEURL (Constant.baseurl). addconverterfact Ory (Gsonconverterfactory.create ()). Addcalladapterfactory (Rxjavacalladapterfactory.create ()) . Client (Getsokhttpclient ()). build (); } } } returnSretrofit; } Public Staticokhttpclient getsokhttpclient () {if(Sokhttpclient = =NULL){ synchronized(Retrofithelper.class){ if(Sokhttpclient = =NULL) {sokhttpclient=NewOkhttpclient.builder (). ConnectTimeout (Default_time_out, Timeunit.seconds) . ReadTimeout (Default_time_out, Timeunit.seconds). WriteTimeout (Default_time_out, Ti meunit.seconds). build (); } } } returnsokhttpclient; }}
3. Open Network Request
Private voidrequestloginnet (String Mobile, string pwd) {//Interface for loginRetrofithelper.getretrofitapi (). Setlogin (Mobile, PWD). Subscribeon (schedulers.i O ()). Observeon (Androidschedulers.mainthread ()). Subscribe (NewObserver<responseinfo<loginbean>>() {@Override Public voidoncompleted () {} @Override Public voidOnError (Throwable e) {} @Override Public voidOnNext (responseinfo<loginbean>response) { if(Response = =NULL){ return; } intresult =Response.getresult (); } }); }
Rxjava+retrofit Implementing Network Requests