Use Kotlin+Rretrofit+rxjava+design pattern+MVP to encapsulate network requests

0. Foreword:

Kotlin is very smooth to use, especially when combined with rxjava and design patterns, you will find that writing code can be so fun! What? Are you still using java? Hurry up and learn kotlin! I believe you will love him, kotlin is also very easy to learn, you can switch from java to kotlin in a day

1. Text

This article mainly introduces how to use kotlin to encapsulate the network request tool, combined with the gorgeous performance of the design pattern ~
not much nonsense, first upload the code:

1. Retrofit management tool

package http;


import android.support.annotation.NonNull;

import com.campus.donview.donviewcampus.App;
import com.google.gson.Gson;

import java.io.IOException;

import beans.response.FindClassBean;
import beans.response.JoinClassBean;
import beans.response.LoginBean;
import beans.response.RegisterBean;
import beans.response.SendCodeBean;
import comment.LogUit;
import interfaces.HttpCallback;
import io.reactivex.Observable;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import static comment.Constant.FIND_CLASS;
import static comment.Constant.JOIN_CLASS;
import static comment.Constant.LOGIN;
import static comment.Constant.REGISTER;
import static comment.Constant.SEND_CODE;

public class RetrofitUtil {
    private static String TAG="RetrofitUtilPrint";
    private static volatile RetrofitUtil retrofitUtil;
    //以okhttp设置客户端,retorfit与okhttp的结合
    private OkHttpClient okHttpClient=new OkHttpClient()
            .newBuilder()
            .addInterceptor(new Interceptor() {
                @NonNull
                @Override
                public Response intercept(@NonNull Chain chain) throws IOException {
                    Request request=chain.request()
                            .newBuilder()
                            .addHeader("Content-Type","application/json;charset=UTF-8")//添加请求头
                            .addHeader("Grpc-Metadata-sessionkey",(App.getInstance().getSession_key()==null?"":App.getInstance().getSession_key()))
                            .build();
                    return chain.proceed(request);
                }
            })
            .build();
    //初始化retrofit
    private Retrofit retrofit=new Retrofit.Builder()
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(HttpAddress.BASE)
            .client(okHttpClient)
            .build();

    //使用单例模式获取retrofitUtli工具
    public static RetrofitUtil getInstance(){
        if (retrofitUtil==null) retrofitUtil=new RetrofitUtil();
        synchronized (RetrofitUtil.class){
            if (retrofitUtil==null) retrofitUtil=new RetrofitUtil();
        }
        return retrofitUtil;
    }

    //网络请求方法的封装
    //Object:传递过来的Bean,HttpCallback:自定义的网络请求回调接口,TYPE:业务请求的类型
    public <T> void requestNet(Object object, HttpCallback callback, int TYPE){
        LogUit.printI(TAG,"object="+object+",typeLogin="+TYPE);
        switch (TYPE){
            //如果是发送验证码的请求
            case SEND_CODE:
                //NetRequest是封装所有请求的retrofit所需的网络请求接口
                NetRequest netRequest = retrofit.create(NetRequest.class);
                //Observable<SendCodeBean>:结合rxjava使用,将返回结果通过rxjava分析
                Observable<SendCodeBean> sendCodeToBeanCall= netRequest.createSend(object);
                //将结果回调
                callback.onResponse(sendCodeToBeanCall,TYPE);
                break;
            //以下方法与此类似(封装嘛,所以行为相似)
            case REGISTER:
                NetRequest netRequest2 = retrofit.create(NetRequest.class);
                Observable<RegisterBean> registerBeanObservable= netRequest2.createRegister(object);
                callback.onResponse(registerBeanObservable,TYPE);
                break;
            case LOGIN:
                NetRequest netRequest3 = retrofit.create(NetRequest.class);
                Observable<LoginBean> loginBeanObservable= netRequest3.createLogin(object);
                callback.onResponse(loginBeanObservable,TYPE);
                break;
            case JOIN_CLASS:
                NetRequest netRequest4 = retrofit.create(NetRequest.class);
                Observable<JoinClassBean> joinClassBeanObservable= netRequest4.createJoin(object);
                callback.onResponse(joinClassBeanObservable,TYPE);
                break;
            case FIND_CLASS:
                NetRequest netRequest5 = retrofit.create(NetRequest.class);
                Observable<FindClassBean> findClassBeanObservable= netRequest5.createFind(object);
                callback.onResponse(findClassBeanObservable,TYPE);
                break;
        }
    }

}


Code analysis:
As mentioned in the comments, the first is to set the retrofit code and a singleton mode to obtain the retrofitUtil code, and then the requestNet method requests the network. The method receives three parameters, the first parameter is the Bean required by the retrofit network request (It is a bean class, different from okhttp, no need to convert to json, all objects inherit from Object), when used, it will be automatically unpacked from object to the corresponding bean class; the second parameter is to encapsulate the custom callback request interface, use To call back the result and use it; the third parameter is the business type,
paste HttpCallback:

package interfaces;

import java.io.IOException;

import io.reactivex.Observable;

public interface HttpCallback {
//使用Observable<T> observable,可以兼容各种请求类型的回调
    <T> void onResponse(Observable<T> observable, int typeLogin);
 
}

Convert the callback data into the corresponding bean class:

package beans.response;

import beans.BaseBean;

public class SendCodeBean{

    /**
     * code : 10000
     * message : send code success
     */

    private int code;
    private String message;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @Override
    public String toString() {
        return "code="+getCode()+",message="+getMessage();
    }
}

The interface required by retrofit request network:



import beans.response.FindClassBean;
import beans.response.JoinClassBean;
import beans.response.LoginBean;
import beans.response.RegisterBean;
import beans.response.SendCodeBean;
import io.reactivex.Observable;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;

public interface NetRequest {
 //POST()里面是访问的网址下的具体位置,SendCodeBean是将回调参数转换的bean类,object为传递过去的数据
    @POST("user/send_code")
    Observable<SendCodeBean> createSend(@Body Object object);

    @POST("user/regist")
    Observable<RegisterBean> createRegister(@Body Object object);

    @POST("user/login")
    Observable<LoginBean> createLogin(@Body Object object);

    @POST("class/join_class")
    Observable<JoinClassBean> createJoin(@Body Object object);

    @POST("class/get_classes")
    Observable<FindClassBean> createFind(@Body Object object);
}

The above is the code that specifically interacts with the network (yes, it was written in java, and I was cheated >_< hahahaha) Uh huh, don’t
worry, come on, let’s see how to use kotlin and rxjava to process the callback data of network requests

2. P in the MVP design pattern - the method of processing data
package present

import android.os.Message

import com.campus.donview.donviewcampus.App
import com.google.gson.Gson

import java.io.IOException
import java.net.ConnectException
import java.net.SocketTimeoutException

import beans.response.LoginBean
import beans.response.RegisterBean
import beans.response.SendCodeBean
import beans.to.LoginToBean
import beans.to.RegisterToBean
import beans.to.SendCodeToBean
import comment.BaseHandler
import comment.LogUit
import comment.SendMessage
import http.HTTPProxy
import interfaces.HttpCallback
import interfaces.RequestCallBack
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Consumer
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers

import comment.Constant.LOGIN
import comment.Constant.REGISTER
import comment.Constant.SEND_CODE

class RegisterPresent//RequestCallBack:封装的回调接口,提高代码兼容性
(private val requestCallBack: RequestCallBack) : HttpCallback {
    private val responseData: String? = null

    //发送验证码
    fun sendCode(sendCodeToBean: SendCodeToBean) {
        //HTTPProxy是网络请求工具的代理,sendCodeToBean是具体传递过去的请求数据,即retrofit的requestNet方法里面的object
        HTTPProxy.getInstance()!!.execute(this, sendCodeToBean, SEND_CODE)
    }

    //注册请求
    fun register(registerToBean: RegisterToBean) {
        //HTTPProxy是网络请求工具的代理,registerToBean是具体传递过去的请求数据,即retrofit的requestNet方法里面的object
        //看吧,使用object作为第一个参数,兼容性强,实现代码封装
        HTTPProxy.getInstance()!!.execute(this, registerToBean, REGISTER)
    }

    //登陆请求
    fun login(loginToBean: LoginToBean) {
        //HTTPProxy是网络请求工具的代理,loginToBean是具体传递过去的请求数据,即retrofit的requestNet方法里面的object
        HTTPProxy.getInstance()!!.execute(this, loginToBean, LOGIN)
    }


    override fun onResponse(responseData: String, typeLogin: Int) {

    }

    //回调方法
    //使用Observable<T> observable方便转换为具体的数据
    override fun <T> onResponse(observable: Observable<T>, typeLogin: Int) {
        try {
            when (typeLogin) {
                SEND_CODE ->
                    //处理验证码请求的回调,转换为Observable<SendCodeBean>,数据包含在SendCodeBean里
                    managerSendCode(observable as Observable<SendCodeBean>)
                LOGIN ->
                    //处理登录请求
                    managerLogin(observable as Observable<LoginBean>)
                REGISTER ->
                    //处理注册请求
                    managerRegister(observable as Observable<RegisterBean>)
            }
        } catch (classException: ClassCastException) {
            classException.printStackTrace()
            LogUit.printE(TAG, "类转换出错=" + classException.message)
        } catch (e: Exception) {
            e.printStackTrace()
            LogUit.printE(TAG, "e=" + e.message)
        }

        LogUit.printI(TAG, "observable=$observable,typeLogin=$typeLogin")
    }


    //验证码回调处理
    private fun managerSendCode(observable: Observable<SendCodeBean>) {
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())//切换到主线程
                .subscribe(object : DisposableObserver<SendCodeBean>() {//处理SendCodeBean

                    override fun onNext(sendCodeBean: SendCodeBean) {
                        LogUit.printI(TAG, "sendCodeBean=" + sendCodeBean.toString())
                        when (sendCodeBean.code) {
                        //请求成功
                            10000 ->
                                //见将结果回调给View
                                requestCallBack.showMessage(100001)
                        //请求参数中有空
                            19997 ->
                                //电话号码为空
                                requestCallBack.showMessage(19997)
                            90004 ->
                                //电话号码不合法
                                requestCallBack.showMessage(90004)
                        }
                    }

                    //请求错误(一般是网络错误)
                    override fun onError(e: Throwable) {
                        LogUit.printE(TAG, "e=$e")
                        requestCallBack.showMessage(-1)
                    }

                    //处理数据后,结束
                    override fun onComplete() {

                    }
                })
    }

    //注册回调
    private fun managerRegister(observable: Observable<RegisterBean>) {
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RegisterBean>() {
                    override fun onNext(registerBean: RegisterBean) {
                        LogUit.printI(TAG, "registerBean=" + registerBean.toString())
                        when (registerBean.code) {
                            10000 -> requestCallBack.showMessage(10000)
                            19997 ->
                                // 请求参数有空 或参数有误 (性别或身份 不正确)
                                requestCallBack.showMessage(19997)
                            90004 ->
                                //电话号码不合法
                                requestCallBack.showMessage(90004)
                            90008 ->
                                // 用户名不合法
                                requestCallBack.showMessage(90008)
                            90001 ->
                                //用户已注册
                                requestCallBack.showMessage(90001)
                            19999 ->
                                //服务器内部错误
                                requestCallBack.showMessage(19999)
                            90007 ->
                                // 验证码不正确
                                requestCallBack.showMessage(90007)
                            90009 ->
                                // 邮件地址不合法
                                requestCallBack.showMessage(90009)
                        }
                    }

                    override fun onError(e: Throwable) {
                        LogUit.printE(TAG, "e=$e")
                        requestCallBack.showMessage(-1)
                    }

                    override fun onComplete() {

                    }
                })
    }

    //登录回调
    private fun managerLogin(observable: Observable<LoginBean>) {
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<LoginBean> {
                    override fun onSubscribe(d: Disposable) {}

                    override fun onNext(loginBean: LoginBean) {
                        LogUit.printI(TAG, "loginBean=" + loginBean.toString())
                        when (loginBean.code) {
                            10000 -> {
                                requestCallBack.showMessage(10000)
                                App.getInstance().session_key = loginBean.session_key
                                App.getInstance().realName = loginBean.user.realname
                            }
                            19997 ->
                                // 请求参数有空 或参数有误 (性别或身份 不正确)
                                requestCallBack.showMessage(19997)
                            19999 ->
                                //内部错误
                                requestCallBack.showMessage(19999)
                            90009 ->
                                // 邮件地址不合法
                                requestCallBack.showMessage(90009)
                            90002 ->
                                // 密码不正确
                                requestCallBack.showMessage(90002)
                            90003 ->
                                // 用户不存在
                                requestCallBack.showMessage(90003)
                        }
                    }

                    override fun onError(e: Throwable) {
                        LogUit.printE(TAG, "e=$e")
                        requestCallBack.showMessage(-1)
                    }

                    override fun onComplete() {}
                })
    }

    override fun onFailure(e: IOException) {}

    override fun onError(code: Int) {}

    companion object {
        private val TAG = "RegisterPrint"
    }

}


What? Don't understand kotlin? The java code also has:

package present;

import android.os.Message;

import com.campus.donview.donviewcampus.App;
import com.google.gson.Gson;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;

import beans.response.LoginBean;
import beans.response.RegisterBean;
import beans.response.SendCodeBean;
import beans.to.LoginToBean;
import beans.to.RegisterToBean;
import beans.to.SendCodeToBean;
import comment.BaseHandler;
import comment.LogUit;
import comment.SendMessage;
import http.HTTPProxy;
import interfaces.HttpCallback;
import interfaces.RequestCallBack;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

import static comment.Constant.LOGIN;
import static comment.Constant.REGISTER;
import static comment.Constant.SEND_CODE;

public class RegisterPresent implements HttpCallback{
    private static final String TAG="RegisterPrint";
    private RequestCallBack requestCallBack;
    private String responseData;
    //RequestCallBack:封装的回调接口,提高代码兼容性
    public RegisterPresent(RequestCallBack requestCallBack){
        this.requestCallBack=requestCallBack;
    }

    //发送验证码
    public void sendCode(SendCodeToBean sendCodeToBean){
        //HTTPProxy是网络请求工具的代理,sendCodeToBean是具体传递过去的请求数据,即retrofit的requestNet方法里面的object
        HTTPProxy.getInstance().execute(this,sendCodeToBean,SEND_CODE);
    }

    //注册请求
    public void register(RegisterToBean registerToBean){
        //HTTPProxy是网络请求工具的代理,registerToBean是具体传递过去的请求数据,即retrofit的requestNet方法里面的object
        //看吧,使用object作为第一个参数,兼容性强,实现代码封装
        HTTPProxy.getInstance().execute(this,registerToBean,REGISTER);
    }

    //登陆请求
    public void login(LoginToBean loginToBean){
        //HTTPProxy是网络请求工具的代理,loginToBean是具体传递过去的请求数据,即retrofit的requestNet方法里面的object
        HTTPProxy.getInstance().execute(this,loginToBean,LOGIN);
    }


    @Override
    public void onResponse(String responseData, int typeLogin) {

    }

    //回调方法
    //使用Observable<T> observable方便转换为具体的数据
    @Override
    public <T> void onResponse(Observable<T> observable, int typeLogin) {
        try {
            switch (typeLogin){
                case SEND_CODE:
                    //处理验证码请求的回调,转换为Observable<SendCodeBean>,数据包含在SendCodeBean里
                    managerSendCode((Observable<SendCodeBean>) observable);
                    break;
                case LOGIN:
                    //处理登录请求
                    managerLogin((Observable<LoginBean>) observable);
                    break;
                case REGISTER:
                    //处理注册请求
                    managerRegister((Observable<RegisterBean>) observable);
                    break;
            }
        }
        catch (ClassCastException classException){
            classException.printStackTrace();
            LogUit.printE(TAG,"类转换出错="+classException.getMessage());
        }
        catch (Exception e){
            e.printStackTrace();
            LogUit.printE(TAG,"e="+e.getMessage());
        }
        LogUit.printI(TAG,"observable="+observable+",typeLogin="+typeLogin);
    }


    //验证码回调处理
    private void managerSendCode(Observable<SendCodeBean> observable){
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())//切换到主线程
                .subscribe(new DisposableObserver<SendCodeBean>() {//处理SendCodeBean

                    @Override
                    public void onNext(SendCodeBean sendCodeBean) {
                        LogUit.printI(TAG,"sendCodeBean="+sendCodeBean.toString());
                        switch (sendCodeBean.getCode()) {
                            //请求成功
                            case 10000:
                                //见将结果回调给View
                                requestCallBack.showMessage(100001);
                                break;
                            //请求参数中有空    
                            case 19997:
                                //电话号码为空
                                requestCallBack.showMessage(19997);
                                break;
                            case 90004:
                                //电话号码不合法
                                requestCallBack.showMessage(90004);
                                break;
                        }
                    }
                    
                    //请求错误(一般是网络错误)
                    @Override
                    public void onError(Throwable e) {
                        LogUit.printE(TAG,"e="+e);
                        requestCallBack.showMessage(-1);
                    }
                    
                    //处理数据后,结束
                    @Override
                    public void onComplete() {

                    }
                });
    }

    //注册回调
    private void managerRegister(Observable<RegisterBean> observable){
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DisposableObserver<RegisterBean>() {
                    @Override
                    public void onNext(RegisterBean registerBean) {
                        LogUit.printI(TAG,"registerBean="+registerBean.toString());
                        switch (registerBean.getCode()){
                            case 10000:
                                requestCallBack.showMessage(10000);
                                break;
                            case 19997:
                                // 请求参数有空 或参数有误 (性别或身份 不正确)
                                requestCallBack.showMessage(19997);
                                break;
                            case 90004:
                                //电话号码不合法
                                requestCallBack.showMessage(90004);
                                break;
                            case 90008:
                                // 用户名不合法
                                requestCallBack.showMessage(90008);
                                break;
                            case 90001:
                                //用户已注册
                                requestCallBack.showMessage(90001);
                                break;
                            case 19999:
                                //服务器内部错误
                                requestCallBack.showMessage(19999);
                                break;
                            case 90007:
                                // 验证码不正确
                                requestCallBack.showMessage(90007);
                                break;
                            case 90009:
                                // 邮件地址不合法
                                requestCallBack.showMessage(90009);
                                break;
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUit.printE(TAG,"e="+e);
                        requestCallBack.showMessage(-1);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    //登录回调
    private void managerLogin(Observable<LoginBean> observable){
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LoginBean>() {
                    @Override
                    public void onSubscribe(Disposable d) { }

                    @Override
                    public void onNext(LoginBean loginBean) {
                        LogUit.printI(TAG,"loginBean="+loginBean.toString());
                        switch (loginBean.getCode()){
                            case 10000:
                                requestCallBack.showMessage(10000);
                                App.getInstance().setSession_key(loginBean.getSession_key());
                                App.getInstance().setRealName(loginBean.getUser().getRealname());
                                break;
                            case 19997:
                                // 请求参数有空 或参数有误 (性别或身份 不正确)
                                requestCallBack.showMessage(19997);
                                break;
                            case 19999:
                                //内部错误
                                requestCallBack.showMessage(19999);
                                break;
                            case 90009:
                                // 邮件地址不合法
                                requestCallBack.showMessage(90009);
                                break;
                            case 90002:
                                // 密码不正确
                                requestCallBack.showMessage(90002);
                                break;
                            case 90003:
                                // 用户不存在
                                requestCallBack.showMessage(90003);
                                break;
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUit.printE(TAG,"e="+e);
                        requestCallBack.showMessage(-1);
                    }

                    @Override
                    public void onComplete() {}
                });
    }

    @Override
    public void onFailure(IOException e) { }

    @Override
    public void onError(int code) { }

}

There are a lot of codes. In order to let everyone see the effect of the encapsulation, I pasted them all. Here we focus on analyzing the verification code request.
As the comment says, the bean containing the data is passed through the network proxy layer by layer through the sendCode method. Pass it over (the code will be given later), until the request method of retrofit, and then process the callback data by implementing the onResponse(observable: Observable, typeLogin: Int) method. The processing method here uses rxjava processing (no If you understand, you can only make up your own brain~~), the advantage of using rxjava is that only one line of code is needed to switch between the sub-thread and the main thread, which can save a lot of code for handle and sendMessage (by the way, you still have to use handle to avoid memory leaks)

3. M in MVP – network request

The packaging of retrofit+okhttp+rxjava has been introduced. Next, let’s continue to introduce how to use design patterns to make the code more "beautiful"
.

Proxy class:

package http

import interfaces.HTTPProxyFace
import interfaces.HttpCallback
import interfaces.HttpInterfaceMode

class HTTPProxy : HTTPProxyFace {
    //    private HttpInterfaceMode httpInterfaceMode=new HttpMode();//HttpMode是使用Okhttp编写的网络请求mode
    private val httpInterfaceMode = RetrofitMode()//RetrofitMode是使用retrofit编写的网络请求mode

    //执行所有类型的网络请求的方法
    override fun execute(callback: HttpCallback, `object`: Any, TYPE: Int) {
        httpInterfaceMode.execute(callback, `object`, TYPE)
    }

    companion object {
        @Volatile
        private var httpProxy: HTTPProxy? = null

        //单例模式获取对象
        val instance: HTTPProxy?
            get() {
                if (httpProxy == null) httpProxy = HTTPProxy()
                synchronized(HTTPProxy::class.java) {
                    if (httpProxy == null) httpProxy = HTTPProxy()
                }
                return httpProxy
            }
    }
}

  • java code...
package http;

import interfaces.HTTPProxyFace;
import interfaces.HttpCallback;
import interfaces.HttpInterfaceMode;

public class HTTPProxy implements HTTPProxyFace {
//    private HttpInterfaceMode httpInterfaceMode=new HttpMode();//HttpMode是使用Okhttp编写的网络请求mode
    private HttpInterfaceMode httpInterfaceMode=new RetrofitMode();//RetrofitMode是使用retrofit编写的网络请求mode
    private static volatile HTTPProxy httpProxy;

    //单例模式获取对象
    public static HTTPProxy getInstance(){
        if (httpProxy==null) httpProxy=new HTTPProxy();
        synchronized (HTTPProxy.class){
            if (httpProxy==null) httpProxy=new HTTPProxy();
        }
        return httpProxy;
    }

    //执行所有类型的网络请求的方法
    @Override
    public void execute(HttpCallback callback,Object object, int TYPE) {
        httpInterfaceMode.execute(callback,object,TYPE);
    }
}

Specific Mode:

package http

import interfaces.HttpCallback
import interfaces.HttpInterfaceMode

class RetrofitMode : HttpInterfaceMode {

    override fun execute(callback: HttpCallback, `object`: Any, TYPE: Int) {
        RetrofitUtil.getInstance().requestNet<Any>(`object`, callback, TYPE)
    }
}


  • java.
package http;

import interfaces.HttpCallback;
import interfaces.HttpInterfaceMode;

public class RetrofitMode implements HttpInterfaceMode {

    @Override
    public void execute(HttpCallback callback, Object object, int TYPE) {
        //看吧,具提调用了RetrofitUtil的requestNet方法,将具体参数传递过去
        RetrofitUtil.getInstance().requestNet(object,callback,TYPE);
    }
}


2. Conclusion

There are a lot of codes in this article (copying and pasting directly is not recommended), in order to let readers have an overall understanding of the code (complain, when I packaged the network request at the beginning, I searched it on the Internet, and it was all incomplete codes that could not meet the needs. In the end, I can only encapsulate _ by myself) The key point is:

  • (1) Use rxjava to process the data of retrofit callback:
 @POST("user/send_code")
    Observable<SendCodeBean> createSend(@Body Object object);

Use Observable to convert the callback data into the bean class we are familiar with
(2) Use DisposableObserver to parse the result when using rxjava to parse the data

at last

If you want to become an architect or want to break through the 20-30K salary range, then don't be limited to coding and business, but you must be able to select models, expand, and improve programming thinking. In addition, a good career plan is also very important, and the habit of learning is very important, but the most important thing is to be able to persevere. Any plan that cannot be implemented consistently is empty talk.

If you have no direction, here I would like to share with you a set of "Advanced Notes on the Eight Major Modules of Android" written by the senior architect of Ali, to help you organize the messy, scattered and fragmented knowledge systematically, so that you can systematically and efficiently Master the various knowledge points of Android development.
insert image description here
Compared with the fragmented content we usually read, the knowledge points of this note are more systematic, easier to understand and remember, and are arranged strictly according to the knowledge system.

Full set of video materials:

1. Interview collection

insert image description here
2. Source code analysis collection
insert image description here

3. The collection of open source frameworks
insert image description here
welcomes everyone to support with one click and three links. If you need the information in the article, directly scan the CSDN official certification WeChat card at the end of the article to get it for free↓↓↓

Guess you like

Origin blog.csdn.net/YoungOne2333/article/details/129867627