RxJava结合Retrofit和Volley简单比较
通过使用Retrofit+RxJava和Volley获取知乎日报消息,比较两者的使用区别。

文中 RR:代指Retrofit+Rxjava
主要两个方面使用
- 使用两者获取Json数据,使用Gson解析。
- 使用两者获取网络图片
1.第一步添加RR和Volley的gradle依赖
//google's volley
compile 'com.mcxiaoke.volley:library:1.0.19'
//RxAndroid
compile 'io.reactivex:rxandroid:1.2.1'
//RxJava
compile 'io.reactivex:rxjava:1.2.3'
//Retrofit
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
2.分析知乎首页Api返回的Json格式


3.构建bean
在AndroidStudio里我是使用一个Json2Pojo插件,可以直接将Json对象转换为适合Gson的JavaBean

在AS的插件管理里可以直接安装 Json2Pojo
/**
* 知乎当日消息
*/
public class Stories {
//供 Google Analytics 使用
@SerializedName("ga_prefix")
private String mGaPrefix;
//url 与 share_url 中最后的数字(应为内容的 id)
@SerializedName("id")
private Long mId;
//图像地址(官方 API 使用数组形式。目前暂未有使用多张图片的情形出现,曾见无 images 属性的情况,请在使用中注意 )
@SerializedName("images")
private List<String> mImages;
//消息是否包含多张图片(仅出现在包含多图的新闻中)
@SerializedName("multipic")
private Boolean mMultipic;
//消息标题
@SerializedName("title")
private String mTitle;
//作用未知
@SerializedName("type")
private Long mType;
public Stories(String mGaPrefix, Long mId, List<String> mImages, Boolean mMultipic, String mTitle, Long mType) {
this.mGaPrefix = mGaPrefix;
this.mId = mId;
this.mImages = mImages;
this.mMultipic = mMultipic;
this.mTitle = mTitle;
this.mType = mType;
}
public void setGaPrefix(String mGaPrefix) {
this.mGaPrefix = mGaPrefix;
}
public void setId(Long mId) {
this.mId = mId;
}
public void setImages(List<String> mImages) {
this.mImages = mImages;
}
public void setMultipic(Boolean mMultipic) {
this.mMultipic = mMultipic;
}
public void setTitle(String mTitle) {
this.mTitle = mTitle;
}
public void setType(Long mType) {
this.mType = mType;
}
public String getGaPrefix() {
return mGaPrefix;
}
public Long getId() {
return mId;
}
public List<String> getImages() {
return mImages;
}
public Boolean getMultipic() {
return mMultipic;
}
public String getTitle() {
return mTitle;
}
public Long getType() {
return mType;
}
@Override
public String toString() {
return "Stories{" +
"mGaPrefix='" + mGaPrefix + '\'' +
", mId=" + mId +
", mImages=" + mImages +
", mMultipic=" + mMultipic +
", mTitle='" + mTitle + '\'' +
", mType=" + mType +
'}';
}
}
4.定义Retrofit和Volley的单例管理
获取Retrofit单例
public class RetrofitManager {
static final String BASE_URL = "http://news-at.zhihu.com/api/4/news/";
private Retrofit retrofit;
private static RetrofitManager ourInstance = new RetrofitManager();
public static RetrofitManager getInstance() {
return ourInstance;
}
private RetrofitManager() {
}
/**
* 获取retrofit单例
*
* @return Retrofit single
*/
public Retrofit getRetrofit() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
获取Volley RequestQueue单例
public class VolleyManager {
private RequestQueue requestQueue;
private static VolleyManager ourInstance = new VolleyManager();
public static VolleyManager getInstance() {
return ourInstance;
}
private VolleyManager() {
}
/**
* 获取 volley requestQueue 单例
*
* @param context activity
* @return volley requestQueue
*/
public RequestQueue getRequestQueue(Context context) {
if (requestQueue == null) {
requestQueue = Volley.newRequestQueue(context);
}
return requestQueue;
}
}
5.定义Retrofit REST Api 接口
//获取Json数据
public interface GetNews {
@GET("latest")
Observable<Result> getNews();
}
//获取图片
public interface GetBitmap {
@GET
Observable<ResponseBody> getPicFromNet(@Url String url);
}
这里使用RxJava形式的接口定义,直接返回 被观察者对象
6.获取Json数据,并返回Result对象
通过RR获取
//get data by Retrofit & RxJava
private void getDataByRetrofit() {
progressBar.setVisibility(View.VISIBLE);
storiesAdapter.setGetPicByRR(true);// tell adapter get pic by retrofit
//RR:Retrofit+RxJava
Subscriber<Result> subscriber = new Subscriber<Result>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
}
@Override
public void onStart() {
super.onStart();
storiesList.clear();
}
//设置数据到RecyclerView
@Override
public void onNext(Result result) {
storiesList.addAll(result.getStories());
storiesAdapter.notifyDataSetChanged();
progressBar.setVisibility(View.INVISIBLE);
}
};
//主要逻辑
GetNews getNews = RetrofitManager.getInstance().getRetrofit().create(GetNews.class);
getNews.getNews()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
}
通过Volley获取
/**
* get data by volley
*/
private void getDataByVolley() {
progressBar.setVisibility(View.VISIBLE);
storiesAdapter.setGetPicByRR(false);// tell adapter get pic by volley
//主要逻辑
StringRequest stringRequest = new StringRequest(Request.Method.GET,
RetrofitManager.BASE_URL + "latest",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//Json to Bean
Gson gson = new Gson();
Result result = gson.fromJson(response, Result.class);
storiesList.addAll(result.getStories());
//设置数据到RecyclerView
storiesAdapter.notifyDataSetChanged();
progressBar.setVisibility(View.INVISIBLE);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
VolleyManager.getInstance().getRequestQueue(this.getApplication()).add(stringRequest);
}
7.Adapter中获取图片
通过RR获取
//get pic by Retrofit and RxJava
Action1<Bitmap> bitmapAction1 = new Action1<Bitmap>() {
@Override
public void call(Bitmap bitmap) {
holder.ivImg.setImageBitmap(bitmap);
}
};
String url = stories.getImages().get(0);
GetBitmap getBitmap = RetrofitManager.getInstance().getRetrofit().create(GetBitmap.class);
getBitmap.getPicFromNet(url)
.map(new Func1<ResponseBody, Bitmap>() {
@Override
public Bitmap call(ResponseBody responseBody) {
//decode pic
return BitmapFactory.decodeStream(responseBody.byteStream());
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(bitmapAction1);
通过Volley获取
//get pic by volley
ImageLoader imageLoader = new ImageLoader(VolleyManager.getInstance()
.getRequestQueue(context.getApplicationContext())
, new ImageLoader.ImageCache() {
@Override
public Bitmap getBitmap(String url) {
return null;
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
}
});
ImageLoader.ImageListener imageListener = ImageLoader.getImageListener(holder.ivImg, R.mipmap.ic_launcher, R.mipmap.ic_launcher);
String url = stories.getImages().get(0);
imageLoader.get(url, imageListener);

8.总结
这里只是从简单的使用层面上对比了RR和Volley两者使用上的不同,之前获取网络数据的任务都是交给Volley来做。
有时获取了A数据之后,马上需要进行下一步包装分析A之后获取B数据。
如果是在Volley中就会出现嵌套的逻辑;在RxJava中使用Retrofit就可以使用它的map(或flatMap)进行A数据的包装分析,之后返回B数据的,就不会出现嵌套的逻辑。
以上只是小生简单的对比,用以自身理解RxJava,有什么不对的地方欢迎各位指出 _
9.整体代码放在GitHub上,欢迎浏览
RxJava结合Retrofit和Volley简单比较的更多相关文章
- RxJava 与 Retrofit 结合的最佳实践
转自:http://gank.io/post/56e80c2c677659311bed9841?from=timeline&isappinstalled=0&nsukey=g1D1Y6 ...
- Android开发okhttp,retrofit,android-async-http,volley?
okhttp, retrofit,android-async-http,volley这四个框架适用的场合?优缺点?各位大大,请给一些建议.我准备开发一个新的APP 如果是标准的RESTful API, ...
- RxJava整合Retrofit遇到的问题总结
一:初上手(填坑) Observable将事件序列执行完毕后,会回调Observe的onNext()方法和onCompleted()方法,当出现异常/错误时会调用onError()方法. 由此,我们推 ...
- Kotlin封装RxJava与Retrofit
代码地址:https://github.com/DarkPointK/RxTrofit.git 前言 Retrofit是Square公司开发的一个类型安全的Java和Android 的REST客户端库 ...
- (转载)RxJava 与 Retrofit 结合的最佳实践
RxJava 与 Retrofit 结合的最佳实践 作者:tough1985 感谢 DaoCloud 为作者提供的 500 RMB 写作赞助: 成为赞助方 /开始写作 前言 RxJava和Retrof ...
- rxjava 调用retrofit执行网络请求的过程
retrofit流程图 -1.RxJava调用Retrofit,从requestGtPushSaeUserInfo()中获得被观察者observable,然后new一个观察者向它订阅 0.从业务中 ...
- [Android] 转-RxJava+MVP+Retrofit+Dagger2+Okhttp大杂烩
原文url: http://blog.iliyun.net/2016/11/20/%E6%A1%86%E6%9E%B6%E5%B0%81%E8%A3%85/ 这几年来android的网络请求技术层出不 ...
- Rxjava, RxAndroid, Retrofit 等库的使用
RxJava的基本用法: 关于 unSubscribe() 的调用问题: There is no need to unsubscribe in onCompleted. Take a look at ...
- RxJava开发精要8 – 与REST无缝结合-RxJava和Retrofit
原文出自<RxJava Essentials> 原文作者 : Ivan Morgillo 译文出自 : 开发技术前线 www.devtf.cn 转载声明: 本译文已授权开发者头条享有独家转 ...
随机推荐
- php分享三十三:常量
一:常量定义 1:在脚本执行期间该值不能改变(除了所谓的魔术常量,它们其实不是常量) 2:常量默认为大小写敏感 3:命名规则:用正则表达式是这样表达的:[a-zA-Z_\x7f-\xff][a-zA- ...
- Configuring Service Broker for Asynchronous Processing
Configuring Service Broker for Asynchronous Processing --create a database and enable the database f ...
- python常用数据类型内置方法介绍
熟练掌握python常用数据类型内置方法是每个初学者必须具备的内功. 下面介绍了python常用的集中数据类型及其方法,点开源代码,其中对主要方法都进行了中文注释. 一.整型 a = 100 a.xx ...
- C#反射的应用
项目框架中有一个很实用的方法,它用来获取客户端post的数据,并自动赋值到对象各属性,这样后台少写了很多代码.但是对于有主表.子表的表单,框架中没有提供自动给子表对象各属性赋值的方法,每次都要写很多代 ...
- 安装、部署... Windows服务 .net程序 安装 命令
@echo offInstallutil.exe 程序目录 F:\test\TestWindows.exe 服务程序目录@sc start "服务名称"@sc config &qu ...
- eclipse中改变默认的workspace的方法及说明
eclipse中改变默然的workspace的方法可以有: 1.在创建project的时候,手动选择使用新的workspace,如创建一个web project,在向导中的Location选项,取消使 ...
- C#十五子游戏
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...
- SignalR-入门
1.什么是SignalR: ASP.NET SignalR是为简化开发开发人员将实时web内容添加到应用程序过程而提供的类库.实时web功能指的是让服务器代码可以随时主动推送内容给客户端,而不是让服务 ...
- js实现向上滚动效果
源码: <style type="text/css"> #up_zzjs{border:1px solid #ccc;width:170px;height:182px; ...
- ASP.NET Web API通过ActionFilter来实现缓存
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Sys ...