准备
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta3'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3' //已经包含了gson
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
compile 'io.reactivex:rxjava:1.1.0'
compile 'io.reactivex:rxandroid:1.1.0'
compile 'com.squareup.okio:okio:1.6.0'
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.2.0' // 看log需要
关键代码
1.定义api接口
public interface CodeHubService {
@GET("/v2/showcases")
Observable<ArrayList<ShowCase>> getShowCaseList();
}
2.创建Retrofit
private Retrofit mRetrofit;
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
Log.d("CodeHubServiceManager", message);
}
});
// 自定义gson解析(List不需要也能自己解析)
// Type showCaseType = new TypeToken<ArrayList<ShowCase>>(){}.getType();
// Gson gson = new GsonBuilder().registerTypeAdapter(showCaseType,
// new JsonDeserializer<ArrayList<ShowCase>>() {
// @Override
// public ArrayList<ShowCase> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
// return new Gson().fromJson(json, typeOfT);
// }
// }).create();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(loggingInterceptor) // 拦截器
.connectTimeout(20, TimeUnit.SECONDS)
.build();
mRetrofit = new Retrofit.Builder()
.baseUrl("http://trending.codehub-app.com")
.client(okHttpClient) // okHttpClient实例,不调用使用默认
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
3. 调用api接口,获取Observable,并进行相关设置,调用subscribe
private CodeHubService mCodeHubService;
mCodeHubService = mRetrofit.create(CodeHubService.class);
Observable<ArrayList<ShowCase>> showCaseObservable = codeHubService.getShowCaseList()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.unsubscribeOn(Schedulers.io()); // 此处注意,***On每个调用返回的都是新的Observable
showCaseObservable .subscribe(new Subscriber<ArrayList<ShowCase>>() {
@Override
public void onCompleted() {
Toast.makeText(getContext(), "onCompleted", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(Throwable e) {
Toast.makeText(getContext(), "onError " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
@Override
public void onNext(ArrayList<ShowCase> showCases) {
Toast.makeText(getContext(), "showCases size=" + showCases.size(), Toast.LENGTH_SHORT).show();
showCaseAdapter.updateData(showCases);
}
});
填坑
- Observable的subscribeOn,observeOn,unsubscribeOn是返回新的对象,而不是修改
参考
http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0106/2275.html (Okhttp基本使用)
http://jakewharton.github.io/butterknife/
http://square.github.io/retrofit/
网友评论