Android Retrofit2+Rxjava2初步使用

记录一下自己使用retrofit2+rxjava2的过程

首先需要导入对应的依赖:

	//retrofit rxjava
    implementation '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形式
    @GET("/api的url")
    Observable getData(@QueryMap Map 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 getData(Map map){
        return serviceApi.getData(map);
    }
}

在需要网络请求的时候调用如下:

		//map存放传入参数,可以多个
		Map 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() {
            	//执行onNext后执行 
                @Override
                public void onCompleted() {
                    Toast.makeText(MaiActivity.this,"onCompleted!",Toast.LENGTH_LONG).show();
                }
				//请求失败
                @Override
                public void onError(Throwable e) {
                    Toast.makeText(RetrofitActivity.this,"请求失败!"+e.getMessage(),Toast.LENGTH_LONG).show();
                    Log.e("请求失败:",""+e.getMessage());
                }
				//请求成功
                @Override
                public void onNext(Bean bean) {
                    Log.e("	请求的数据",bean.toString());
                    //对数据处理的逻辑...
                }
            });

你可能感兴趣的:(Android开发记录)