您的当前位置:首页RXJava+retrofit的使用尝试
RXJava+retrofit的使用尝试
来源:锐游网
首先引入依赖包:
compile 'io.reactivex:rxjava:1.1.0'
compile 'io.reactivex:rxandroid:1.1.0'
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.jakewharton:butterknife:7.0.1'
建立一个请求接口后面可使用代理模式实例化:
public interface TestService {
@GET("posts")
Observable<List<NewsBean>> gettask(@Query("t") String cate, @Query("b") String cate2);
// @GET("posts")
// Call<List<NewsBean>> gettask(@Query("t") String cate, @Query("b") String cate2);
}
参照gsonfactory重写方法:
package com.cheerchip.rxjavaretrofit;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.List;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.converter.gson.*;
/**
* Created by noname on 2017/6/2.
*/
public class GsonFormat1 extends Converter.Factory {
/**
* Create an instance using a default {@link Gson} instance for conversion. Encoding to JSON and
* decoding from JSON (when no charset is specified by a header) will use UTF-8.
*/
public static GsonFormat1 create() {
return create(new Gson());
}
/**
* Create an instance using {@code gson} for conversion. Encoding to JSON and
* decoding from JSON (when no charset is specified by a header) will use UTF-8.
*/
@SuppressWarnings("ConstantConditions") // Guarding public API nullability.
public static GsonFormat1 create(Gson gson) {
if (gson == null) throw new NullPointerException("gson == null");
return new GsonFormat1(gson);
}
private final Gson gson;
private GsonFormat1(Gson gson) {
this.gson = gson;
}
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
//TypeToken typeToken=new TypeToken().
TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
return new GsonResponseBodyConverter<>(gson, adapter);
}
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
TypeToken<List<NewsBean>> typetoken=new TypeToken<List<NewsBean>>(){};
Type type1=typetoken.getType();
// TypeToken.
TypeAdapter<?> adapter = gson.getAdapter(typetoken);
return new GsonRequestBodyConverter<>(gson, adapter);
}
}
第二个类:
package com.cheerchip.rxjavaretrofit;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.Converter;
/**
* Created by noname on 2017/6/2.
*/
class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
private final Gson gson;
private final TypeAdapter<T> adapter;
GsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
this.gson = gson;
this.adapter = adapter;
}
@Override public T convert(ResponseBody value) throws IOException {
// JsonReader jsonReader = gson.newJsonReader(value.charStream());
//gson.
// Log.e("convert: ",value.string());
String json=value.string();
Log.e("convert1: ",json);
JSONArray jsonarray= null;
try {
JSONObject jsonobj=new JSONObject(json);
JSONObject jsondata= jsonobj.getJSONObject("data");
jsonarray = jsondata.getJSONArray("posts");
} catch (JSONException e) {
e.printStackTrace();
}
//jsonReader.
try {
return adapter.fromJson(jsonarray.toString());
} finally {
value.close();
}
}
}
第三个类:
package com.cheerchip.rxjavaretrofit;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import retrofit2.Converter;
/**
* Created by noname on 2017/6/2.
*/
final class GsonRequestBodyConverter<T> implements Converter<T, RequestBody> {
private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
private static final Charset UTF_8 = Charset.forName("UTF-8");
private final Gson gson;
private final TypeAdapter<T> adapter;
GsonRequestBodyConverter(Gson gson, TypeAdapter<T> adapter) {
this.gson = gson;
this.adapter = adapter;
}
@Override public RequestBody convert(T value) throws IOException {
Buffer buffer = new Buffer();
Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
JsonWriter jsonWriter = gson.newJsonWriter(writer);
adapter.write(jsonWriter, value);
jsonWriter.close();
return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
}
}
仿照着写就能解析自己的json格式了。
自己的bean类:
package com.cheerchip.rxjavaretrofit;
import java.util.List;
/**
* Created by noname on 2017/6/2.
*/
public class NewsBean {
/**
* id : 140768
* title : 第39期:马德兴独家爆料解析,中国申世还要多久
* authorId : 904
* sourceUrl :
* sourceName : 肆客足球App
* commentCount : 27
* likeCount : 15
* shareCount : 0
* visibleStatus : 1
* channelType : 19
* imageType : 1
* itemType : 1
* time : 3074201580000
* originalPublishDate : 1496364791000
* toTop : 1
* redirectId : 0
* redirectType : 0
* label : 超级颜论
* enableComment : true
* toHome : 1
* summary : 一样的足球,不一样的颜论。
* redirectUrl :
* heatValue : 7346
* contentImagesCount : 3
* recommend : 0
* imageUrls : ["http://cdn.qiudd.net/36_1496337700_1496338173102.jpeg?imageView2/1/w/230/h/146"]
* imageSizes : [[0,0]]
* videoId : 0
*/
private int id;
private String title;
private int authorId;
private String sourceUrl;
private String sourceName;
private int commentCount;
private int likeCount;
private int shareCount;
private int visibleStatus;
private int channelType;
private int imageType;
private int itemType;
private long time;
private long originalPublishDate;
private int toTop;
private int redirectId;
private int redirectType;
private String label;
private boolean enableComment;
private int toHome;
private String summary;
private String redirectUrl;
private int heatValue;
private int contentImagesCount;
private int recommend;
private int videoId;
private List<String> imageUrls;
private List<List<Integer>> imageSizes;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getAuthorId() {
return authorId;
}
public void setAuthorId(int authorId) {
this.authorId = authorId;
}
public String getSourceUrl() {
return sourceUrl;
}
public void setSourceUrl(String sourceUrl) {
this.sourceUrl = sourceUrl;
}
public String getSourceName() {
return sourceName;
}
public void setSourceName(String sourceName) {
this.sourceName = sourceName;
}
public int getCommentCount() {
return commentCount;
}
public void setCommentCount(int commentCount) {
this.commentCount = commentCount;
}
public int getLikeCount() {
return likeCount;
}
public void setLikeCount(int likeCount) {
this.likeCount = likeCount;
}
public int getShareCount() {
return shareCount;
}
public void setShareCount(int shareCount) {
this.shareCount = shareCount;
}
public int getVisibleStatus() {
return visibleStatus;
}
public void setVisibleStatus(int visibleStatus) {
this.visibleStatus = visibleStatus;
}
public int getChannelType() {
return channelType;
}
public void setChannelType(int channelType) {
this.channelType = channelType;
}
public int getImageType() {
return imageType;
}
public void setImageType(int imageType) {
this.imageType = imageType;
}
public int getItemType() {
return itemType;
}
public void setItemType(int itemType) {
this.itemType = itemType;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public long getOriginalPublishDate() {
return originalPublishDate;
}
public void setOriginalPublishDate(long originalPublishDate) {
this.originalPublishDate = originalPublishDate;
}
public int getToTop() {
return toTop;
}
public void setToTop(int toTop) {
this.toTop = toTop;
}
public int getRedirectId() {
return redirectId;
}
public void setRedirectId(int redirectId) {
this.redirectId = redirectId;
}
public int getRedirectType() {
return redirectType;
}
public void setRedirectType(int redirectType) {
this.redirectType = redirectType;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public boolean isEnableComment() {
return enableComment;
}
public void setEnableComment(boolean enableComment) {
this.enableComment = enableComment;
}
public int getToHome() {
return toHome;
}
public void setToHome(int toHome) {
this.toHome = toHome;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getRedirectUrl() {
return redirectUrl;
}
public void setRedirectUrl(String redirectUrl) {
this.redirectUrl = redirectUrl;
}
public int getHeatValue() {
return heatValue;
}
public void setHeatValue(int heatValue) {
this.heatValue = heatValue;
}
public int getContentImagesCount() {
return contentImagesCount;
}
public void setContentImagesCount(int contentImagesCount) {
this.contentImagesCount = contentImagesCount;
}
public int getRecommend() {
return recommend;
}
public void setRecommend(int recommend) {
this.recommend = recommend;
}
public int getVideoId() {
return videoId;
}
public void setVideoId(int videoId) {
this.videoId = videoId;
}
public List<String> getImageUrls() {
return imageUrls;
}
public void setImageUrls(List<String> imageUrls) {
this.imageUrls = imageUrls;
}
public List<List<Integer>> getImageSizes() {
return imageSizes;
}
public void setImageSizes(List<List<Integer>> imageSizes) {
this.imageSizes = imageSizes;
}
@Override
public String toString() {
return "NewsBean{" +
"id=" + id +
", title='" + title + '\'' +
", authorId=" + authorId +
", sourceUrl='" + sourceUrl + '\'' +
", sourceName='" + sourceName + '\'' +
", commentCount=" + commentCount +
", likeCount=" + likeCount +
", shareCount=" + shareCount +
", visibleStatus=" + visibleStatus +
", channelType=" + channelType +
", imageType=" + imageType +
", itemType=" + itemType +
", time=" + time +
", originalPublishDate=" + originalPublishDate +
", toTop=" + toTop +
", redirectId=" + redirectId +
", redirectType=" + redirectType +
", label='" + label + '\'' +
", enableComment=" + enableComment +
", toHome=" + toHome +
", summary='" + summary + '\'' +
", redirectUrl='" + redirectUrl + '\'' +
", heatValue=" + heatValue +
", contentImagesCount=" + contentImagesCount +
", recommend=" + recommend +
", videoId=" + videoId +
", imageUrls=" + imageUrls +
", imageSizes=" + imageSizes +
'}';
}
}
使用gsonformat可以实现。
Retrofit retrofit= new Retrofit.Builder()
.baseUrl("http://server.qiuduoduo.cn")
.addConverterFactory(GsonFormat1.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
TestService service =retrofit.create(TestService.class);
创建了一个retrofit实例使用代理模式生成了testservice对象;
下面或得了被观察者对象并在线程中操作了数据流
Observable<List<NewsBean>> observable= service.gettask("zc","");
observable.
flatMap(new Func1<List<NewsBean>, Observable<?>>() {
@Override
public Observable<?> call(List<NewsBean> newsBeen) {
Log.e( "onCompleted1: ", (Looper.getMainLooper()==Looper.myLooper())+"");
return Observable.from(newsBeen);
}
})
.map(new Func1<Object, Object>() {
@Override
public Object call(Object o) {
Log.e("call1: ", ((NewsBean) o).toString());
Log.e( "onCompleted2: ", (Looper.getMainLooper()==Looper.myLooper())+"");
return ((NewsBean) o);
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Subscriber<Object>() {
@Override
public void onCompleted() {
Log.e( "onCompleted3: ", (Looper.getMainLooper()==Looper.myLooper())+"");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Object o) {
}
})
因篇幅问题不能全部显示,请点此查看更多更全内容