//rxjava和retrofit
implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
implementation 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
implementation 'io.reactivex:rxandroid:1.2.0'
public interface RetrofitService {
//登录
@POST(HttpUrl.LOGIN_URL)
@FormUrlEncoded
Observable login(@Field("phone") String phone, @Field("pwd") String pwd);
//注册
@POST(HttpUrl.REGISTER_URL)
@FormUrlEncoded
Observable register(@Field("phone") String phone, @Field("pwd") String pwd);
//banner
@GET(HttpUrl.BANNER_URL)
Observable banner();
//获取首页
@GET(HttpUrl.HOME_GOODS_URL)
Observable information();
//我的足迹
@GET(HttpUrl.FOOTMARK_URL)
Observable footMark(@Query("page") int page, @Query("count") int count, @Header("sessionId") String sessionId, @Header("userId") int userId);
//我的商品列表归属标签查询商品信息
@GET(HttpUrl.GOODS_LIST)
Observable getGoodsList(@Query("labelId") String labelId,@Query("page") int page, @Query("count") int count);
}
public class RetrofitUtls {
private static RetrofitUtls instance;
private Retrofit mretrofit;
private RetrofitUtls() {
mretrofit = new Retrofit.Builder()
.baseUrl(HttpUrl.BASE_URL) //baseurl必须以/结尾
.addConverterFactory(GsonConverterFactory.create()) //添加数据解析器,即序列化器
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(OkHttpUtil.okHttpClient) //指定http客户端
.build();
}
//单例模式
public static RetrofitUtls getInstance() {
if (instance == null) {
instance = new RetrofitUtls();
}
return instance;
}
//泛型
public T createApi(Class cls){
T t=mretrofit.create(cls);
return t;
}
}
public class HomeModel {
public void showHome(String keywords, final HomeCallBack homeCallBack){
DataService service = RetrofitUtil.getInstance().createApi(DataService.class);
service.showHome(keywords).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
homeCallBack.onHomeFailer("错误");
}
@Override
public void onNext(HomeEntity homeEntity) {
List data = homeEntity.getData();
homeCallBack.onHomeSuccess(data);
}
});
}
public void ondestroy() {
}
}