记录一下自己使用retrofit2+rxjava2的过程
首先需要导入对应的依赖:
//retrofit rxjavaimplementation 'io.reactivex:rxjava:1.1.5'implementation 'com.squareup.retrofit2:retrofit:2.3.0'implementation 'com.squareup.retrofit2:converter-gson:2.3.0'implementation 'com.squareup.okhttp3:okhttp:3.10.0'implementation 'com.squareup.okhttp3:logging-interceptor:3.5.0'implementation 'com.squareup.retrofit2:adapter-rxjava:2.1.0'implementation 'io.reactivex:rxandroid:1.1.0'
新建一个接口,存放所有的api
ServiceApi:
public interface ServiceApi {//不包含基地址 //Bean是返回数据的实体类 //@QueryMap代表传入多个参数 不确定个数 以Map<key,value>形式@GET("/api的url")Observable<Bean> getData(@QueryMap Map<String,String> map);
}
创建RetrofitHelper封装一下初始化retrofit
RetrofitHelper:
public class RetrofitHelper {Context mContext;public RetrofitHelper(Context context){mContext = context;}OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(2, TimeUnit.MINUTES).writeTimeout(2, TimeUnit.MINUTES).readTimeout(2, TimeUnit.MINUTES).build();Retrofit retrofit = new Retrofit.Builder().baseUrl("/baseUrl")//基地址.client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();ServiceApi serviceApi = retrofit.create(ServiceApi.class);public Observable<Bean> getData(Map<String,String> map){return serviceApi.getData(map);}
}
在需要网络请求的时候调用如下:
//map存放传入参数,可以多个Map<String,String> map = new HashMap<>();map.put("key","value");RetrofitHelper retrofitHelper = new RetrofitHelper(MaiActivity.this);retrofitHelper.getData(map).subscribeOn(Schedulers.io())//IO线程.observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Bean>() {//执行onNext后执行 @Overridepublic void onCompleted() {Toast.makeText(MaiActivity.this,"onCompleted!",Toast.LENGTH_LONG).show();}//请求失败@Overridepublic void onError(Throwable e) {Toast.makeText(RetrofitActivity.this,"请求失败!"+e.getMessage(),Toast.LENGTH_LONG).show();Log.e("请求失败:",""+e.getMessage());}//请求成功@Overridepublic void onNext(Bean bean) {Log.e(" 请求的数据",bean.toString());//对数据处理的逻辑...}});