Retrofit + Rxandroid

Retrofit提供了相关的接口;

implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0'

修改Retrofit实例

Retrofit retrofit = new Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create())
        .baseUrl("http://ip.tianqiapi.com/")
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .build();

.addCallAdapterFactory(RxJava2CallAdapterFactory.create())

添加后Retrofit接口中可以返回Observable<T>,原本是返回Call<T>;

用IP做个例子:

public interface GetIpService2 {
    @GET("/")
    Observable<IpResult2> getIpInfo2(
            @Query("ip") String ip
    );
}

使用Rxandroid

GetIpService2 IGetIp = retrofit.create(GetIpService2.class);
Observable<IpResult2> observableResult = IGetIp.getIpInfo2("21.22.11.33");
observableResult
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Consumer<IpResult2>() {
            @Override
            public void accept(IpResult2 ipResult2) throws Exception {
                Log.v(TAG, "accept");
                if (ipResult2 != null) {
                    Log.v(TAG, "##" + ipResult2.getIp() + ", " + ipResult2.getCountry());
                }
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                Log.v(TAG, "Exception:" + throwable);
            }
        });

运行LOG:

V/x999x: accept
V/x999x: ##21.22.11.33, 美国

简单的封装

管理类:用来缓存各Retrofit实例;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

import retrofit2.Retrofit;

public class RetrofitApiManager {
    private HashMap<Class, Retrofit> mRetrofitServiceHashMap = new HashMap<>();
    private ConcurrentHashMap<Class, Object> cachedApis = new ConcurrentHashMap<>();

    private static RetrofitApiManager I;

    private RetrofitApiManager() {}

    public static synchronized RetrofitApiManager getI() {
        if (I == null) {
            I = new RetrofitApiManager();
        }

        return I;
    }

    public <T> void addService(Class<T> clz, Retrofit retrofit) {
        mRetrofitServiceHashMap.put(clz, retrofit);
    }

    public <T> T getService(Class<T> clz) {
        Object obj = cachedApis.get(clz);
        if (obj != null) {
            return (T) obj;
        } else {
            Retrofit retrofit = mRetrofitServiceHashMap.get(clz);
            if (retrofit != null) {
                T service = retrofit.create(clz);
                cachedApis.put(clz, service);
                return service;
            } else {
                return null;
            }
        }
    }
}

服务类:用来负责Retrofit的一些实际配置和Rxandroid的实际处理;

import android.util.Log;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class GetIpService2Impl {
    private static final String TAG = "x999x";

    private static String BASE_URL = "http://ip.tianqiapi.com/";

    private static GetIpService2Impl I;

    private  GetIpService2Impl() {}

    public static GetIpService2Impl getI() {
        if (I == null) {
            Retrofit retrofit = new Retrofit.Builder()
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(BASE_URL)
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();

            RetrofitApiManager.getI().addService(GetIpService2.class, retrofit);
            I = new GetIpService2Impl();
        }
        return I;
    }

    public void getIpInfo(String ip) {
        RetrofitApiManager.getI().getService(GetIpService2.class).getIpInfo2(ip)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<IpResult2>() {
                    @Override
                    public void accept(IpResult2 ipResult2) throws Exception {
                        Log.v(TAG, "accept");
                        if (ipResult2 != null) {
                            Log.v(TAG, "##" + ipResult2.getIp() + ", " + ipResult2.getCountry());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Log.v(TAG, "Exception:" + throwable);
                    }
                });
    }
}

在需要的地方调用:

GetIpService2Impl.getI().getIpInfo("21.22.11.33");

进过简单封装之后,调用代码会看起来更简洁;

猜你喜欢

转载自blog.csdn.net/weixin_39821531/article/details/88951414