retrofit2、RxJava简单使用总结

需要引入的依赖包括:

compile 'com.squareup.retrofit2:retrofit:2.0.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.0'

compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.squareup.okio:okio:1.6.0'

compile 'io.reactivex:rxandroid:1.1.0'

这里不要遗漏converter-gson,或者可以使用simplexml解析

retrofit2在创建adapter时如需返回Observable需要注册CallAdapterFactory,这里和retrofit有区别,返回Callback不需要注册。

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(okHttpClient)
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .addConverterFactory(GsonConverterFactory.create())
        .build();

接口定义:

public interface ApiService {
    @GET("Android/{pageSize}/{pageCount}")
    Observable<Response> users(@Path("pageSize")int pageSize, @Path("pageCount") int pageCount);
}

调用:

api = retrofit.create(ApiService.class);

Observable.just(params)
        .flatMap(new Func1<Map<String, Integer>, Observable<Response>>() {
            @Override
            public Observable<Response> call(Map<String, Integer> stringObjectMap) {
                return api.users(stringObjectMap.get("pageSize"),stringObjectMap.get("pageCount"));
            }
        })
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Action1<Response>() {
            @Override
            public void call(ReceiveData response) {
                usersInfoList = response.results;
                listAdapter.notifyDataSetChanged();
            }
        });


你可能感兴趣的:(rxjava)