1.工具类
package com.example.utils;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
public class HttpUtils {
private static HttpUtils httpUtils = new HttpUtils();
private Retrofit retrofit;
private HttpUtils(){
init();
}
public static HttpUtils getHttpUtils(){
if(httpUtils == null){
httpUtils = new HttpUtils();
}
return httpUtils;
}
private void init() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.connectTimeout(60,TimeUnit.SECONDS)
.writeTimeout(10,TimeUnit.SECONDS)
.readTimeout(10,TimeUnit.SECONDS)
.build();
retrofit = new Retrofit.Builder()
.client(okHttpClient)
.baseUrl("http://172.17.8.100/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
public <T> T create(final Class<T> service){
return retrofit.create(service);
}
}
2.Presenter层
父类
package com.example.presenter;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
public abstract class BasePresenter {
private Consumer consumer;
public BasePresenter(Consumer consumer){
this.consumer = consumer;
}
protected abstract Observable observable(Object...args);
public void request(Object...args){
observable(args).subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(consumer);
}
}
子类
package com.example.presenter;
import com.example.core.ILogin;
import com.example.utils.HttpUtils;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
public class MyPresenter extends BasePresenter {
public MyPresenter(Consumer consumer) {
super(consumer);
}
@Override
protected Observable observable(Object... args) {
ILogin iLogin = HttpUtils.getHttpUtils().create(ILogin.class);
return iLogin.login((String)args[0],(String)args[1]);
}
}
3.接口
public interface ILogin {
@POST("small/user/v1/login")
@FormUrlEncoded
Observable<Result<User>> login(@Field("phone") String phone,
@Field("pwd") String password);
}
4.Rxjava 和Retrofit所需的依赖
/*retrofig 网络请求*/
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
/*okhttp 网络请求*/
implementation 'com.squareup.okhttp3:okhttp:3.12.1'
/*rxjava*/
implementation 'io.reactivex.rxjava2:rxjava:2.2.4'
/*rxandroid*/
implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'
/*网络解析gson*/
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'