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) {
                       

                    }
                });

猜你喜欢

转载自blog.csdn.net/qq_42120002/article/details/81138346
今日推荐