Rxjava2+retrofit2+golang

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

said in front of my ability Limited, hope master do not spray.

Golang

Golang language, also known as Go language, is a language developed by Google to accommodate high concurrency and development efficiency. The syntax of the go language is very simple and suitable for server-side development. So I'm going to use Golang to do the web backstage. Because this section focuses not on the go language. So it will be more simple to introduce.

RxJava

Rxjava also used for a long time, always want to record some use process, but because of time problem, has not written. Rxjava is a link-style programming experience that you'll love when you use it. I've been using RXJAVA1 for a long time, but in November 2016 the official RXJAVA2, and version 1 is not being maintained, so I'll use version 2 here.

Retrofit

Retrofit is a network request framework that is a re-encapsulation of the okhttp framework. Provide a good use experience. I'm using the retrofit2 here.

Server-side

Server side I used a framework for the go language, which is an open-source framework written by two foreigners and is very handy for writing APIs, gin.

package mainimport (    "blog/src/enity"    "fmt"    "github.com/gin-gonic/gin")func main() {    gin.SetMode(gin.ReleaseMode)    router := gin.Default()    router.POST("/", func(c *gin.Context) {        start := c.PostForm("start")        count := c.PostForm("count")        fmt.Println("start: ", start, "  count:", count)        c.JSON(200, gin.H{            "code": "201",            "msg":  "success",            "data": gin.H{                "name":    "aa",                "age":     25,                "address": "成都",                "sex":     1},        })    })    router.Run(":8000")}

This server-side interface is very simple to get a JSON data.

App side

Introducing Dependencies

    //rxjava2 和rxAndroid    compile 'io.reactivex.rxjava2:rxjava:2.1.1'    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'    //retrofit2    compile 'com.squareup.retrofit2:retrofit:2.3.0'   // 自动解析json数据为实体的包     compile 'com.squareup.retrofit2:converter-gson:2.3.0'   //retrofit支持转换为Rxjava的包    compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'   //okhttp    compile 'com.squareup.okhttp3:okhttp:3.3.0'    compile 'com.squareup.okio:okio:1.8.0'    compile 'com.google.code.gson:gson:2.8.1'

There is a observer type in Rxjava this is an observer, a class that processes data. Another is the observable class, which is the class of the observer, and the class that the class is to produce the data. In the Apiservice interface class, the method GetUser () Returns an observer, and the type uses generics, that is, we can automatically parse the JSON data into our entity object.

Create a new Apiservice interface class

public interface ApiService {    @Multipart    @POST("/")    Observable<BaseResponseDto<User>> getUser(@Part("start") int start, @Part("count") int count);}

We used the result API style interface, and generally our interface returned the JSON data format to.

{    code: "200",    msg: "success",    data: {    }}

So we can encapsulate this data.

public class BaseResponseDto<T> {    private String code;    private String msg;    private T data;    public String getCode() {        return code;    }    public void setCode(String code) {        this.code = code;    }    public String getMsg() {        return msg;    }    public void setMsg(String mag) {        this.msg = mag;    }    public T getData() {        return data;    }    public void setData(T data) {        this.data = data;    }    @Override    public String toString() {        return "BaseResponseDto{" +                "code='" + code + '\'' +                ", mag='" + msg + '\'' +                ", data=" + data +                '}';    }}

When requesting network data on the app side, we always deal with various anomalies, such as network anomalies, JSON parsing anomalies, and so on, in order to reduce the exception handling code, we need to encapsulate this part. We are using Rxjava so we need to encapsulate the viewer.

Public abstract class Defaultobserver<t extends baseresponsedto> implements observer<t> {private static S    Tring tag= "Defaultobserver";    Private context context;    Private Baseviewimpl Baseview;    Private String message= "";    private disposable disposable;    Public Defaultobserver (Context context) {This.context=context;        } public Defaultobserver (Context Context,baseviewimpl baseview) {this.baseview=baseview;    This.context=context;        } public Defaultobserver (Context context,baseviewimpl baseview,string message) {This.baseview=baseview;        This.message=message;    This.context=context;        } @Override public void Onsubscribe (@NonNull disposable D) {log.i (TAG, "======onsubscribe======");        Disposable=d;            if (Null!=baseview) {baseview.adddisposable (d);        Baseview.showprogressdialog (message); }} @Override public void OnNext (@NonNull T response) {LOG.I (TAG, "= ===onnext====== ");        Mainthread ();            if (Null!=baseview) {baseview.removedisposable (disposable);        Baseview.dismissprogressdialog ();        }else {disposable.dispose ();        } if (Response.getcode (). Equals ("$")) {onsuccess (response);        }else{Onfail (response);         }} @Override public void OnError (@NonNull throwable e) {log.i (TAG, "======onerror======" +e.getmessage ());            if (null!=baseview) {baseview.removedisposable (disposable);        Baseview.dismissprogressdialog ();        }else {disposable.dispose ();        } if (e instanceof httpexception) {///HTTP Error Toastutil.showshort (context, "HTTP Error"); } else if (e instanceof connectexception | | e instanceof unknownhostexception) {//Connection error TOA        Stutil.showshort (Context, "connection error"); } else if (e instanceof interruptedioexception) {//Connection timeout ToaStutil.showshort (Context, "Connection timeout"); } else if (e instanceof jsonparseexception | | e instanceof jsonexception | | e instanceof Par        Seexception) {//Parse error Toastutil.showshort (context, "parse error");        } else if (e instanceof ioexception) {toastutil.showshort (context, "IO error");        }else {toastutil.showshort (context, "unknown error");  }} @Override public void OnComplete () {}/** * Request succeeded * @param response */abstract public    void onsuccess (T response); /** * Data error returned after successful request * @param response */public void Onfail (T response) {Toastutil.showshort (Contex     T,response.getmsg ()); }}

After this encapsulation we only need to implement the Onsuccess () method on the subclass, we only focus on the successful acquisition of the data. You can also copy the Onfail () method if you want to perform a related operation based on your failure.

In the end, we need to get the classes of the previous packages into a network request class, which makes it easy to call outside. A HTPP class was created using the.

public class HTTP {private static final String tag= "http";    private static final String base_url= "Http://127.0.0.1:8000/";    private static final int default_timeout=5;    private static Retrofit Retrofit;    Private Apiservice Apiservice;                Private Http () {Gson Gson = new Gsonbuilder (). Setdateformat ("Yyyy-mm-dd ' T ' HH:mm:ssZ") . Create ();//Use Gson Coverter, Uniform date request format Okhttpclient.builder builder=new Okhttpclient.builder (). Add        Interceptor (New Logginginterceptor ()). ConnectTimeout (Default_timeout, timeunit.seconds);                     Retrofit=new Retrofit.builder (). BASEURL (Base_url). Client (Builder.build ()) . Addconverterfactory (Gsonconverterfactory.create (Gson)). Addcalladapterfactory (RXJAVA2CA        Lladapterfactory.create ()). build ();    Apiservice=retrofit.create (Apiservice.class); } private Static Class Signleholder{private static final HTTP Instance=new http ();    } public static Http getinstance () {return signleholder.instance; } Private class Logginginterceptor implements interceptor{@Override public Response intercept (Chain Chai            N) throws IOException {Request request=chain.request (); LOG.I (Tag,string.format ("\ nthe request:%s on%s \ n%s%s", Request.url (), Chain.connection (), Request.headers (),            Request.body (). ContentType ());            Response response=chain.proceed (Request);            LOG.I (Tag,string.format ("\ n response:%s \ n Body:%s \ n", Response.request (). URL (), ""));        return response; }} public void GetUser (defaultobserver<baseresponsedto<user>> observer) {Apiservice.getuser (0,10 ). Subscribeon (Schedulers.io ()). Observeon (Androidschedulers.mainthread ()). s    UBSCRIBE (Observer); }}

This can be called directly from the HTPP class using the external wrapper.

public void testDefaultRxJava(){        Http.getInstance().getUser(new DefaultObserver<BaseResponseDto<User>>(MainActivity.this,this) {            @Override            public void onSuccess(BaseResponseDto<User> response) {                  Log.i(TAG,"=====onSuccess======"+response.toString());            }            @Override            public void onFail(BaseResponseDto<User> response) {                super.onFail(response);            }        });    }

This makes it easy to implement the RXJAVA2+RETROFIT2 package.

Summary

Reference link http://www.jianshu.com/p/9674f6df910d

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.