Retrofit 和 Rxjava 的结合使用

来源:互联网 发布:汽车销售网站模板 cms 编辑:程序博客网 时间:2024/05/17 00:57

这两天看了下RxJava , 它的操作确实让我们的代码逻辑非常清晰。

而RxJava的解释已经有大牛做了很详细的解释(>http://gank.io/post/560e15be2dca930e00da1083),就不多说了。

它最亮眼的我觉得就是和Retrofit的结合使用,让我们处理数据便的非常方便。下面是Retrofit 和 Rxjava结合使用的简单列子。

引用关键包,Retrofit对RxJava 的支持: compile ‘com.squareup.retrofit2:adapter-rxjava:2.3.0’

  public interface APIService {        @POST("BaikeLemmaCardApi")        Observable<String> getUser(@Query("appid") String userId,@Query("bk_key") String bk_key);    }    private void testRetrofit(){//Retrofit 和 Rxjava的结合使用        Scheduler observeOn = Schedulers.computation(); // Or use mainThread() for Android.        Retrofit retrofit = new Retrofit.Builder()                .baseUrl("http://baike.baidu.com/api/openapi/")                //增加返回值为String的支持                .addConverterFactory(ScalarsConverterFactory.create())//                //增加返回值为Gson的支持(以实体类返回)//                .addConverterFactory(GsonConverterFactory.create())                .addCallAdapterFactory(new ObserveOnMainCallAdapterFactory(observeOn))                .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(io()))                .build();        APIService service = retrofit.create(APIService .class);         service.getUser("379020","接口").subscribe(new Action1<String>() {            @Override            public void call(String s) {                Log.d("KSS","res:"+s);            }        });    }    static final class ObserveOnMainCallAdapterFactory extends CallAdapter.Factory {        final Scheduler scheduler;        ObserveOnMainCallAdapterFactory(Scheduler scheduler) {            this.scheduler = scheduler;        }        @Override        public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {            if (getRawType(returnType) != Observable.class) {                return null; // Ignore non-Observable types.            }            // Look up the next call adapter which would otherwise be used if this one was not present.            //noinspection unchecked returnType checked above to be Observable.            final CallAdapter<Object, Observable<?>> delegate =                    (CallAdapter<Object, Observable<?>>) retrofit.nextCallAdapter(this, returnType,                            annotations);            return new CallAdapter<Object, Object>() {                @Override                public Object adapt(Call<Object> call) {                    // Delegate to get the normal Observable...                    Observable<?> o = delegate.adapt(call);                    // ...and change it to send notifications to the observer on the specified scheduler.                    return o.observeOn(scheduler);                }                @Override                public Type responseType() {                    return delegate.responseType();                }            };        }}