Android RxHttpの実戦での運用


RxHttpとは何かについては、ここでは話さないで、必要なものがあればRxHttpの詳細を見て、Githubは説明します.
RxHttpはどのようにRetrfit+RxJavaのようにチェーン式の複数の要求の移動を実現します
本編では、実戦でどのように運用されているか1、関連ライブラリファイルの導入について説明します
	implementation 'com.rxjava.rxhttp:rxhttp:2.1.0' //  
    annotationProcessor 'com.rxjava.rxhttp:rxhttp-compiler:2.1.0' //     ,  RxHttp ,  
    implementation 'com.rxjava.rxlife:rxlife-x:2.0.0'
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.8.0'

2、JDK 8をサポートする
	compileOptions {
     
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

3、工具類
import android.text.TextUtils;
import androidx.fragment.app.FragmentActivity;
import com.rxjava.rxlife.RxLife;

import java.io.File;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import rxhttp.wrapper.annotation.DefaultDomain;
import rxhttp.wrapper.entity.Progress;
import rxhttp.wrapper.param.RxHttp;

/**
 * FileName: RxhttpUtil
 * Author: admin
 * Date: 2020/5/14 15:27
 * Description:
 */
public class RxhttpUtil {
     

    @DefaultDomain
    public static String baseUrl = "http://www.baidu.com/";

    private static volatile RxhttpUtil instance = null;

    public static RxhttpUtil getInstance() {
     
        if (instance == null) {
     
            synchronized (RxhttpUtil.class) {
     
                if (instance == null) {
     
                    instance = new RxhttpUtil();
                }
            }
        }
        return instance;
    }

    /**
     *    RxHttp
     *
     * @param debug false: debug  ,true:debug  
     * @param url     BaseUrl
     */
    public static void init(boolean debug, String url) {
     
        if (!TextUtils.isEmpty(url)) {
     
            baseUrl = url;
        }
        setOkhttp(debug);
    }

    /**
     *    RxHttp
     *
     * @param debug false: debug  ,true:debug  
     */
    public static void init(boolean debug) {
     
        setOkhttp(debug);
    }

    private static void setOkhttp(boolean debug) {
     
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .readTimeout(30 * 1000, TimeUnit.MILLISECONDS)
                .writeTimeout(30 * 1000, TimeUnit.MILLISECONDS)
                .connectTimeout(30 * 1000, TimeUnit.MILLISECONDS);
        /**
         *       
         */
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        builder.addInterceptor(loggingInterceptor);
        RxHttp.init(builder.build(), debug);
    }

    /**
     * get   
     *
     * @param url              
     * @param a
     * @param httpCallBack
     */
    public void get(String url, FragmentActivity a, RxHttpCallBack httpCallBack) {
     
        RxHttp.get(url)
                .asString()
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.asOnMain(a))
                .subscribe(new Observer<String>() {
     
                    @Override
                    public void onSubscribe(Disposable d) {
     
                        httpCallBack.onStart();
                    }

                    @Override
                    public void onNext(String s) {
     
                        httpCallBack.onSuccess(s);
                    }

                    @Override
                    public void onError(Throwable e) {
     
                        httpCallBack.onError(e.getMessage());
                    }

                    @Override
                    public void onComplete() {
     
                        httpCallBack.onFinish();
                    }
                });
    }

    /**
     * get   
     *
     * @param url              
     * @param map              
     * @param a
     * @param httpCallBack
     */
    public void get(String url, Map<String, String> map, FragmentActivity a, RxHttpCallBack httpCallBack) {
     
        RxHttp.get(url)
                .addAll(map)
                .asString()
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.asOnMain(a))
                .subscribe(new Observer<String>() {
     
                    @Override
                    public void onSubscribe(Disposable d) {
     
                        httpCallBack.onStart();
                    }

                    @Override
                    public void onNext(String s) {
     
                        httpCallBack.onSuccess(s);
                    }

                    @Override
                    public void onError(Throwable e) {
     
                        httpCallBack.onError(e.getMessage());
                    }

                    @Override
                    public void onComplete() {
     
                        httpCallBack.onFinish();
                    }
                });
    }

    /**
     * get  
     *
     * @param url                
     * @param map                
     * @param rxBaseResponse          
     * @param a
     * @param httpResponse
     */
    public void get(String url, Map<String, String> map, RxBaseResponse rxBaseResponse, FragmentActivity a, RxHttpResponse httpResponse) {
     
        RxHttp.get(url)
                .addAll(map)
                .asResponse(rxBaseResponse.getClass())
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.asOnMain(a))
                .subscribe(new Observer<RxBaseResponse>() {
     
                    @Override
                    public void onSubscribe(Disposable d) {
     
                        httpResponse.onStart();
                    }

                    @Override
                    public void onNext(RxBaseResponse rxBaseResponse) {
     
                        httpResponse.onSuccess(rxBaseResponse);
                    }

                    @Override
                    public void onError(Throwable e) {
     
                        httpResponse.onError(e.getMessage());
                    }

                    @Override
                    public void onComplete() {
     
                        httpResponse.onFinish();
                    }
                });
    }

    /**
     * post  
     *
     * @param url              
     * @param map              
     * @param a
     * @param httpCallBack
     */
    public void post(String url, Map<String, String> map, FragmentActivity a, RxHttpCallBack httpCallBack) {
     
        RxHttp.postForm(url)
                .addAll(map)
                .asString()
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.asOnMain(a))
                .subscribe(new Observer<String>() {
     
                    @Override
                    public void onSubscribe(Disposable d) {
     
                        httpCallBack.onStart();
                    }

                    @Override
                    public void onNext(String s) {
     
                        httpCallBack.onSuccess(s);
                    }

                    @Override
                    public void onError(Throwable e) {
     
                        httpCallBack.onError(e.getMessage());
                    }

                    @Override
                    public void onComplete() {
     
                        httpCallBack.onFinish();
                    }
                });
    }

    /**
     * post  
     *
     * @param url              
     * @param map              
     * @param baseResponse          
     * @param a
     * @param httpCallBack
     */
    public void post(String url, Map<String, String> map, RxBaseResponse baseResponse, FragmentActivity a, RxHttpResponse httpCallBack) {
     
        RxHttp.postForm(url)
                .addAll(map)
                .asObject(baseResponse.getClass())
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.asOnMain(a))
                .subscribe(new Observer<RxBaseResponse>() {
     
                    @Override
                    public void onSubscribe(Disposable d) {
     
                        httpCallBack.onStart();
                    }

                    @Override
                    public void onNext(RxBaseResponse s) {
     
                        httpCallBack.onSuccess(s);
                    }

                    @Override
                    public void onError(Throwable e) {
     
                        httpCallBack.onError(e.getMessage());
                    }

                    @Override
                    public void onComplete() {
     
                        httpCallBack.onFinish();
                    }
                });
    }

    /**
     * post    
     *
     * @param url              
     * @param map              
     * @param a
     * @param httpCallBack
     */
    public void postFrom(String url, Map<String, String> map, FragmentActivity a, RxHttpCallBack httpCallBack) {
     
        RxHttp.postForm(url)
                .addAll(map)
                .asString()
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.asOnMain(a))     //    ,      
                .subscribe(new Observer<String>() {
     
                    @Override
                    public void onSubscribe(Disposable d) {
     
                        httpCallBack.onStart();
                    }

                    @Override
                    public void onNext(String s) {
     
                        httpCallBack.onSuccess(s);
                    }

                    @Override
                    public void onError(Throwable e) {
     
                        httpCallBack.onError(e.getMessage());
                    }

                    @Override
                    public void onComplete() {
     
                        httpCallBack.onFinish();
                    }
                });
    }

    /**
     *     
     *
     * @param url            
     * @param key          key
     * @param filePath         
     * @param rxHttpFile     
     */
    public void uploadFile(String url, String key, String filePath, FragmentActivity a, RxHttpFile rxHttpFile) {
     
        RxHttp.postForm(url) //  Form     Post  
                .addFile(key, new File(filePath))
                .asUpload(new Consumer<Progress>() {
     
                    @Override
                    public void accept(Progress progress) throws Exception {
     
                        rxHttpFile.onProgress(progress.getProgress(), progress.getCurrentSize(), progress.getTotalSize());
                    }
                }, AndroidSchedulers.mainThread())
                .as(RxLife.asOnMain(a))
                .subscribe(new Observer<String>() {
     
                    @Override
                    public void onSubscribe(Disposable d) {
     
                        rxHttpFile.onStart();
                    }

                    @Override
                    public void onNext(String s) {
     
                        rxHttpFile.onSuccess(s);
                    }

                    @Override
                    public void onError(Throwable e) {
     
                        rxHttpFile.onError(e.getMessage());
                    }

                    @Override
                    public void onComplete() {
     
                        rxHttpFile.onFinish();
                    }
                });
    }

    /**
     *     
     *
     * @param httpUrl           
     * @param filePath         
     * @param a        activity
     * @param httpFile     
     */
    public void downloadFile(String httpUrl, String filePath, FragmentActivity a, RxHttpFile httpFile) {
     
        RxHttp.get(httpUrl)
                .asDownload(filePath, new Consumer<Progress>() {
     
                    @Override
                    public void accept(Progress progress) throws Exception {
     
                        httpFile.onProgress(progress.getProgress(), progress.getCurrentSize(), progress.getTotalSize());
                    }
                }, AndroidSchedulers.mainThread()) //       
                .as(RxLife.asOnMain(a))
                .subscribe(new Observer<String>() {
     
                    @Override
                    public void onSubscribe(Disposable d) {
     
                        httpFile.onStart();
                    }

                    @Override
                    public void onNext(String s) {
     
                        httpFile.onSuccess(s);
                    }

                    @Override
                    public void onError(Throwable e) {
     
                        httpFile.onError(e.getMessage());
                    }

                    @Override
                    public void onComplete() {
     
                        httpFile.onFinish();
                    }
                });
    }

    /**
     *       ,          
     *
     * @param a
     * @param url1        
     * @param url2        
     * @param map1           
     * @param map2           
     */
    public void post(FragmentActivity a, String url1, String url2, Map<String, String> map1, Map<String, String> map2, RxHttpCallBack callBack) {
     
        RxHttp.postForm(url1)
                .addAll(map1)
                .asString()
                .flatMap(new Function<String, ObservableSource<?>>() {
     
                    @Override
                    public ObservableSource<?> apply(String s) throws Exception {
     
                        return RxHttp.get(url2)
                                .addAll(map2)
                                .subscribeOnCurrent()
                                .asString();
                    }
                })
                .as(RxLife.asOnMain(a))
                .subscribe(new Observer<Object>() {
     
                    @Override
                    public void onSubscribe(Disposable d) {
     
                        callBack.onStart();
                    }

                    @Override
                    public void onNext(Object o) {
     
                        callBack.onSuccess(o.toString());
                    }

                    @Override
                    public void onError(Throwable e) {
     
                        callBack.onError(e.toString());
                    }

                    @Override
                    public void onComplete() {
     
                        callBack.onFinish();
                    }
                });
    }

    public interface RxHttpCallBack {
     
        /**
         *     
         */
        void onStart();

        /**
         *     
         *
         * @param response
         */
        void onSuccess(String response);

        /**
         *     
         *
         * @param error
         */
        void onError(String error);

        /**
         *     
         */
        void onFinish();
    }

    public interface RxHttpResponse {
     
        /**
         *     
         */
        void onStart();

        /**
         *     
         *
         * @param response
         */
        void onSuccess(RxBaseResponse response);

        /**
         *     
         *
         * @param error
         */
        void onError(String error);

        /**
         *     
         */
        void onFinish();
    }

    public interface RxHttpFile {
     
        /**
         *     
         */
        void onStart();

        /**
         *     
         *
         * @param response
         */
        void onSuccess(String response);

        /**
         *          
         *
         * @param progress        
         * @param currentSize           
         * @param totalSize        
         */
        void onProgress(int progress, long currentSize, long totalSize);

        /**
         *     
         *
         * @param error
         */
        void onError(String error);

        /**
         *     
         */
        void onFinish();
    }
}

リクエスト結果がオブジェクトに戻る必要がある場合は、単純にカプセル化できます.
public abstract class RxBaseResponse<T> {
     
    private int code;
    private String msg;
    private T data;

    public int getCode() {
     
        return code;
    }

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

    public String getMsg() {
     
        return msg;
    }

    public void setMsg(String msg) {
     
        this.msg = msg;
    }

    public T getData() {
     
        return data;
    }

    public void setData(T data) {
     
        this.data = data;
    }
}

ぶんせきき
@Parser(name = "Response")
public class RxResponseParser<T> extends AbstractParser<T> {
     

    protected RxResponseParser() {
     
        super();
    }

    public RxResponseParser(Type type) {
     
        super(type);
    }

    @Override
    public T onParse(okhttp3.Response response) throws IOException {
     
        final Type type = ParameterizedTypeImpl.get(RxBaseResponse.class, mType); //      
        RxBaseResponse<T> data = convert(response, type);
        T t = data.getData(); //  data  
        if (data.getCode() != 200 || t == null) {
     //    code   200,       ,    
            throw new ParseException(String.valueOf(data.getCode()), data.getMsg(), response);
        }
        return t;
    }
}

挨拶終わりました!