Retrofit + RxJava 的结合使用

Retrofit + RxJava火了好一阵子了,网上也有很多博客,下面对之前的学习经验做一些总结,权当记笔记了,若是能够帮到看到的人,那也是很高兴的。
对于Retrofit不熟悉,可以查看 Retrofit官网,也可以查看我写的 Retrofit学习笔记
对于RxJava不熟悉,可以查看 扔物线 大神的 给 Android 开发者的 RxJava 详解
闲话少说,直接奔主题:

1、在builde.gradle(Moudle:app)中添加如下依赖
compile 'io.reactivex:rxjava:1.1.0'
compile 'io.reactivex:rxandroid:1.1.0'

compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
2、在AndroidManifest.xml中添加网络权限
<uses-permission android:name="android.permission.INTERNET"/>
3、 Retrofit 与 RxJava 的结合
3.1、单独使用Retrofit是这样的:
Retrofit.Builder builder = new Retrofit.Builder();
HttpApi httpApi = builder.baseUrl(HttpUtils.BaseURL)
                          .addConverterFactory(GsonConverterFactory.create())
                          .build()
                          .create(HttpApi.class);

Map<String, String> keyMap = null;
keyMap = new HashMap<>();
keyMap.put("offset","10");
keyMap.put("limit","0");
keyMap.put("isShowTimeOutMission","false");

httpApi.getData(keyMap).enqueue(new Callback<Response>() {
        @Override
        public void onResponse(Call<Response> call, retrofit2.Response<Response> response) {}

        @Override
        public void onFailure(Call<Response> call, Throwable t) {}
});
上述代码中HttpApi.class的代码如下,注意这里getData()返回的数据类型为Call:
/**
 * Created by bai-qiang.yang on 2017/3/6.
 */

public interface HttpApi {

    @FormUrlEncoded
    @POST("/install-mission/update-task")
    public abstract Call<Response> getData(@FieldMap Map<String,String> keyMap);
}
3.2、Retrofit 与 RxJava 结合使用是这样的:
3.2.1、添加如下依赖(这里之前我已经添加过了):
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
3.2.2、代码如下(注意添加了创建builder对象时addCallAdapterFactory(RxJavaCallAdapterFactory.create())方法):
Retrofit.Builder builder = new Retrofit.Builder();
        HttpApi httpApi = builder.baseUrl(HttpUtils.BaseURL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build()
                .create(HttpApi.class);

        Map<String, String> keyMap = null;
        keyMap = new HashMap<>();
        keyMap.put("offset","10");
        keyMap.put("limit","0");
        keyMap.put("isShowTimeOutMission","false");

        Observable<Response> observable = httpApi.getData(keyMap);
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Response>() {
                    @Override
                    public void onCompleted() {
                        System.out.println("onCompleted------>");
                    }

                    @Override
                    public void onError(Throwable e) {
                        System.out.println("error---->"+e.getMessage());
                    }

                    @Override
                    public void onNext(Response response) {
                        /**在这里改变UI*/
                        System.out.println("msg---->"+response.getMsg());
                    }
                });
上述代码中HttpApi.class的代码如下,注意这里getData()返回的数据类型为Observable:
/**
 * Created by bai-qiang.yang on 2017/3/6.
 */

public interface HttpApi {
    @FormUrlEncoded
    @POST("/install-mission/update-task")
    public abstract Observable<Response> getData(@FieldMap Map<String,String> map);
}
这样Retrofit和RxJava就结合在一起了,下面是我写的一个简单的封装:
/**
 * Created by bai-qiang.yang on 2017/3/6.
 */

public class HttpManager {

    private Retrofit mRetrofit;
    private HttpApi mHttpApi;
    public static String BaseURL = "http://app.reward.test.utouu.com";

    //搞成单例
    public HttpManager() {}

    public static final HttpManager httpManager = new HttpManager();

    public static HttpManager getInstance() {
        return  httpManager;
    }

    public <T> T initRetrofit(Class<T> T) {

        if (mRetrofit == null) {
            mRetrofit = new Retrofit.Builder()
                    .baseUrl(BaseURL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .build();
        }
        T t = mRetrofit.create(T);
        return t;
    }


    public <T> void toSubscribe(Observable o,Subscriber<T> s){
                o.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s);
    }
}

上述代码中HttpApi.class的代码如下:

/**
 * Created by bai-qiang.yang on 2017/3/6.
 */

public interface HttpApi {

    @FormUrlEncoded
    @POST("/install-mission/update-task")
    public abstract Observable<Response> getData(@FieldMap Map<String,String> keyMap);
}
使用如下:
        Map<String, String> keyMap = null;
        keyMap = new HashMap<>();
        keyMap.put("offset","10");
        keyMap.put("limit","0");
        keyMap.put("isShowTimeOutMission","false");

        if (mInstance == null) {
            mInstance = HttpManager.getInstance();
        }

        if (mObservable == null) {
            mObservable = mInstance
                    .initRetrofit(HttpApi.class)
                    .getData(keyMap);
        }

        mInstance.toSubscribe(mObservable, new Subscriber<Response>() {
            @Override
            public void onCompleted() {
                System.out.println("complete---->");
            }

            @Override
            public void onError(Throwable e) {
                System.out.println("error---->"+e.getMessage());
            }

            @Override
            public void onNext(Response response) {
                /**在这里更新UI*/
                System.out.println("msg---->"+response.getMsg());
            }
        });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值