Retrofit2 + RxJava 中出现的问题

来源:互联网 发布:nginx error log 关闭 编辑:程序博客网 时间:2024/05/21 22:24

环境说明:

compile 'io.reactivex:rxandroid:1.1.0'compile 'io.reactivex:rxjava:1.1.0'compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'

使用 rxJava、rxAndroid 1.1.0版本
使用retrofit2 2.0.0-beta4版本

1、还需要增加okhttp3、和okio的依赖吗?
不需要,retrofit2已经默认增加了okhttp3,okio的依赖,所以我们的项目不需要再声明okhttp3、okio的依赖。
2、怎么增加调试信息?
以前的老版本,在retrofit对象上有listener方法,可以对retrofit进行监听,并打印一些Debug信息,但在beta4版本中,没有这样的方法以供增加监听,所以只能在Okhttp3上设置一个Interceptor来打印一些需要的日志。

HttpLoggingInterceptor logging = new HttpLoggingInterceptor();// set your desired log levellogging.setLevel(HttpLoggingInterceptor.Level.BODY);// add your other interceptors …// add logging as last interceptorOkHttpClient client = new OkHttpClient.Builder()           .addInterceptor(logging)           .build();Retrofit retrofit = new Retrofit.Builder()                .baseUrl(BASE_URL)                .client(client)                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())                .addConverterFactory(FastJsonConverterFactory.create())                .build();

3、打印出来的日志,只有只有发送,没有回执,用浏览器都能看到返回值的。

03-09 09:11:34.609 13471-13491/com.xxxxxx.carcare D/OkHttp: <-- 200 OK http://192.168.0.46:8080/users/56c2c40d77ce6f9a3c73a09e (2692ms)03-09 09:11:34.639 13471-13491/com.xxxxxx.carcare D/OkHttp: <-- END HTTP (82-byte body)

这个是因为,Rx的缘故,Rx默认会进行线程调度。默认的线程是Rx线程池里的,网络请求需要放到io线程中,而返回后的结果需要在main线程里操作。
需要在Observable上配置线程调度

.observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())

4、使用FastJson作为序列化工具
参见本人的另一篇文章。

http://blog.csdn.net/soslinken/article/details/50832958

0 0
原创粉丝点击