Android rxjava和Retrofit的使用
阿新 • • 發佈:2018-12-14
1.第一步將Retrofit和Rxjava關聯起來 public Retrofit getRetrofit(String baseUrl){ Retrofit retrofit=new Retrofit.Builder() .client(setOkHttpClick()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl(baseUrl) .build(); return retrofit;
2.把Retrofit的返回值替換為Retrofit的Observer物件
public interface BeautyServer { @POST Observable<TodayNewsRes> getBeauty(@Url String url); } 3.呼叫介面返回資料 RetrofitClient.getInstance().getRetrofit(BASE_URL).create(BeautyServer.class).getBeauty("api/today") .subscribeOn(Schedulers.newThread()) .observeOn(Schedulers.io())//工作執行緒 .doOnNext(new Action1<TodayNewsRes>() { @Override public void call(TodayNewsRes todayNewsRes) { Logger.d(todayNewsRes); } }) .observeOn(AndroidSchedulers.mainThread())//切換為主執行緒返回資料 .subscribe(new Subscriber<TodayNewsRes>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(TodayNewsRes todayNewsRes) { toastMsg(todayNewsRes.toString()); //Logger.d(todayNewsRes.toString()); } });