Rxjava2与Retrofit2的使用

首先在学习他们的结合使用前,我们需要简单的学习它们:
Rxjava2的简单使用与基本操作符
Retrofit2网络框架的使用
这里我使用了Bmob作为简单的后台管理,通过登录案列以便查看

一 配置

//rxjava2
compile 'io.reactivex.rxjava2:rxjava:2.1.10'
compile 'io.reactivex.rxjava2:rxandroid:2.0.2'

//retrofit2
 compile 'com.squareup.retrofit2:retrofit:2.3.0'
//Retrofit到Gson进行转换的库
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
//Retrofit到RxJava进行转换的库
compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
//如果需要添加HttpLoggingInterceptor进行调试,添加如下依赖
compile 'com.squareup.okhttp3:logging-interceptor:3.6.0'
compile 'com.squareup.okhttp3:okhttp-urlconnection:3.2.0'

二 使用

2.1 创建接口

interface HttpInterface {
    //登录
    @GET("1/login")
    Observable login(@QueryMap Map data);
}

2.2 创建Retrofit2工具类

public class RetrofitHttp {
    public static HttpInterface getHttpInterface() {
        //保存cookie信息
        CookieManager cookieManager = new CookieManager();
        cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
        // Retrofit是基于OkHttpClient的,可以创建一个OkHttpClient进行一些配置
        OkHttpClient httpClient = new OkHttpClient.Builder()
            // 添加通用的Header
            .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        Request build = request.newBuilder()
                                //添加headler
                                .addHeader("X-Bmob-Application-Id", "88d31c7422f7bb24b4b162743c436fdc")
                                .addHeader("X-Bmob-REST-API-Key", "d06ffe71668b518ffec6839436d5ed16")
                                .method(request.method(), request.body())
                                .build();
                        return chain.proceed(build);
                    }
                })
                //添加HttpLoggingInterceptor拦截器方便调试接口
                .addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                    @Override
                    public void log(String message) {

                    }
                }).setLevel(HttpLoggingInterceptor.Level.BASIC))
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .cookieJar(new JavaNetCookieJar(cookieManager))
                .retryOnConnectionFailure(true)
                .build();

        return new Retrofit.Builder()
                .baseUrl("https://api.bmob.cn/")
                // 添加Gson转换器
                .addConverterFactory(GsonConverterFactory.create())
                // 添加Retrofit到RxJava的转换器
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(httpClient)
                .build()
                .create(HttpInterface.class);
    }
}

2.3 封装方便调用

public class ApiServer {

    /**
     * 用户登录
     */
    public static void loginModel(Map data, Observer observer) {
        RetrofitHttp.getHttpInterface()
                .login(data)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }
}

2. 4 调用方法,访问网络

Mapmap=new ArrayMap<>();
map.put("username","admin");
map.put("password","admin");
ApiServer.loginModel(map, new Observer() {
    @Override
    public void onSubscribe(@NonNull Disposable d) {
    }
    @Override
    public void onNext(@NonNull User user) {
        Log.i(TAG, "onNext: "+user);
    }
    @Override
    public void onError(@NonNull Throwable e) {
    }
    @Override
    public void onComplete() {
    }
});

你可能感兴趣的:(Rxjava2与Retrofit2的使用)