依赖
//retrofi依赖
compile 'com.squareup.retrofit2:retrofit:+'
compile 'com.squareup.retrofit2:converter-gson:+'
//Rxjava2需要依赖
compile 'io.reactivex.rxjava2:rxjava:+'
compile 'io.reactivex.rxjava2:rxandroid:+'
//让retrofit支持Rxjava2
compile 'com.squareup.retrofit2:adapter-rxjava2:+'
user包
RetrofitApi类存放请求数据是拼接的网络路径
public interface RetrofitApi {
@GET("user/login")
Observable<LoginBean> onLogin(@Query("mobile") String mobile, @Query("password") String password);
}
RetrofitMannager 类是为工具栏,只需要改变跟接口路径就行
/**
* 封装Retrofit网络请求类
*/
public class RetrofitMannager {
private static final String BASEURL = "http://120.27.23.105/";
private static Retrofit mretrofit;
private static RetrofitMannager retrofitMannager;
//提供共有的方法供外界使用返回实例
public static RetrofitMannager newinstance() {
if (retrofitMannager == null) {
retrofitMannager = new RetrofitMannager();
}
return retrofitMannager;
}
//构造器私有化
private RetrofitMannager() {
mretrofit = getRetrofit();
}
//构建自定义OkhttpClient
private static OkHttpClient getOkhttpClient() {
return new OkHttpClient.Builder()
.connectTimeout(5000, TimeUnit.MILLISECONDS)
.build();
}
//构建Retrofit
private static Retrofit getRetrofit() {
return new Retrofit.Builder().baseUrl(BASEURL)
.client(getOkhttpClient())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
//通过动态代理返回网络请求接口实例
public <T> T mreceat(Class<T> t) {
return mretrofit.create(t);
}
}
model层
Model类是为了调用网咯请求数据的类
public class Model {
//请求数据返回RxJava被观察者
public Observable<Mvpbean> onLogin(String mobile, String password) {
return RetrofitMannager.newinstance().mreceat(RetrofitApi.class).onLogin(mobile, password);
}
}
view层
BaseIView类是v层接口的父类,为了方便创建更多v层接口
public interface BaseIView {
}
v层接口
public interface IView extends BaseIView {
void onSucsse(LoginBean loginBean);
void onError(Throwable throwable);
}
Iviews类是p层接口
public abstract class Iviews<T extends BaseIView> {
protected T view;
public Iviews(T view) {
this.view = view;
init();
}
protected abstract void init();
}
Iviews是p层的类
public class Passer extends Iviews<IView> {
private Model model;
public Passer(IView view) {
super(view);
}
@Override
protected void init() {
model = new Model();
}
public void onLoad(String mobile, String password) {
Observable<LoginBean> loginBeanObservable = model.onLogin(mobile, password);
loginBeanObservable
// //被观察者在子线程请求数据
.subscribeOn(Schedulers.io())
//观察者在住线程发生数据给View层
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<LoginBean>() {
@Override
public void accept(LoginBean loginBean) throws Exception {
Passer.super.view.onSucsse(loginBean);
}
},
new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
}
}
);
}
}