RxJava2+Retrofit+缓存简单的使用

 

 
所需的依赖


implementation 'com.google.code.gson:gson:2.8.5'//不用可以不加

    implementation 'com.android.support:design:26.1.0'//不用可以不加

    implementation 'com.squareup.okhttp3:okhttp:3.10.0'//新版本//不用可以不加

    implementation 'com.squareup.retrofit2:retrofit:2.4.0'

    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

    implementation 'com.squareup.retrofit2:adapter-rxjava:2.1.0'

    implementation 'io.reactivex:rxandroid:1.2.1'

    implementation 'io.reactivex:rxjava:1.1.6'

    implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'

 


public interface ApiService {
    @GET("1")
    rx.Observable<Bean>getRx();
}

 


    //普通缓存拦截器
    private   OkHttpClient getCache(Context context) {

        final Cache ch = new Cache(new File(context.getCacheDir(), "ch"), 10240 * 1024);
        return new OkHttpClient.Builder().cache(ch).addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request build = chain.request()
                .newBuilder()
            .cacheControl(new CacheControl.Builder()
        //缓存可以停留的时间
        .maxStale(2,TimeUnit.HOURS).build()).build();                                                                               
                return chain.proceed(build);
            }
        }).build();

    }
 
//使用方式

new Retrofit.Builder()
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl("http://gank.io/api/data/%E7%A6%8F%E5%88%A9/40/")
                .client(getCache(getActivity()))
                .build()
                .create(ApiService.class)
                .getRx()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Bean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        if (null != e) {
                            Log.d("BlankFragment", e.getMessage());
                        }
                    }

                    @Override
                    public void onNext(Bean bean) {
                       

                    }
                });

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值