您的位置:首页 > 移动开发 > Android开发

RxAndroid+Retrofit环境搭建

2016-01-25 17:51 627 查看
Retrofit为我们提供Restful风格的Api,RxAndroid基于RxJava方便我们进行异步操作。

下面分享一下,我搭建Retrofit+RxAndroid 环境的过程:

一、引入依赖的jar包(1,2,3jar包版本要对应,不然可能报错,1,2,3,4不要直接引入源码,要用jar包):

1、okio-1.6.0.jar https://github.com/square/okio

2、okhttp-3.0.0-RC1.jar https://github.com/square/okhttp

3、retrofit-2.0.0-beta3.jar https://github.com/square/retrofit

4、rxjava-1.1.0.jar https://github.com/ReactiveX/RxJava

5、rxandroid由于只有四个类我直接引入的源代码 https://github.com/ReactiveX/RxAndroid

二、retrofit的使用

参考官网:http://square.github.io/retrofit/

官网中直接通过Gson来封装返回结果,所以还需要引入Gson的jar包以及https://github.com/square/retrofit/tree/master/retrofit-converters/gson

(这需要Eclipse 使用Java 1.7进行编译,整个Android项目的project.properties文件的target 也需要android-19或者以上版本,但是支持的Android平台为android 2.3+,这是retrofit在用Maven导出jar包时做了兼容,所以我们不能直接使用源码,而是需要使用通过Maven导出的jar包)

retrofit也可以直接返回String类型需引入:

https://github.com/square/retrofit/tree/master/retrofit-converters/scalars

Retrofit retrofit = new Retrofit.Builder().addConverterFactory(ScalarsConverterFactory.create()).baseUrl(apiUrl).build();


将json转换成gson类:http://www.jsonschema2pojo.org/

三、retrofit和RxAndroid结合使用参考:

http://gank.io/post/560e15be2dca930e00da1083?url_type=39&object_type=webpage&pos=1#toc_26

注意:需要指定subscribeOn的线程,要不然会报

android.os.NetworkOnMainThreadException

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


结合以上说明,应该就可以避免搭建过程中的许多问题,希望对你有帮助。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: