View层
public interface CartView {
void success(int type, String data);
void fail(int type, String data);
}
Model层
public interface CartModel {
interface CallBackListener{
void success(int type, String data);
void fail(int type, String error);
}
void doCart(int type, String url, CallBackListener listener);
}
实现Model接口
public class CartModelIm implements CartModel{
@Override
public void doCart(final int type, String url, final CallBackListener listener) {
new HttpUtil().get(url).result(new HttpListener() {
@Override
public void success(String data) {
listener.success(type,data);
}
@Override
public void fail(String error) {
listener.fail(type,error);
}
});
}
}
Presenter层
public interface CartPresenter {
void doCart(int type, String url);
}
实现P层接口
public class CartPresenterIm implements CartPresenter,CartModel.CallBackListener {
CartModel model;
CartView view;
public CartPresenterIm(CartModel model, CartView view) {
this.model = model;
this.view = view;
}
@Override
public void doCart(int type, String url) {
model.doCart(type,url,this);
}
@Override
public void success(int type, String data) {
view.success(type, data);
}
@Override
public void fail(int type, String error) {
view.fail(type, error);
}
public void destory(){
if(view != null){
view = null;
}
if(model != null) {
model = null;
}
System.gc();
}
}
工具类
public class HttpUtil {
public HttpUtil get(String url){
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
Cache cache = new Cache(file, 10 * 1024);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
return chain.proceed(request);
}
})
.cache(cache)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://172.17.8.100/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(client)
.build();
CartService service = retrofit.create(CartService.class);
service.getCart(url)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(ResponseBody responseBody) {
try {
listener.success(responseBody.string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onError(Throwable e) {
listener.fail(e.getMessage());
}
@Override
public void onComplete() {
}
});
return this;
}
private HttpListener listener;
public void result(HttpListener listener) {
this.listener = listener;
}
}
工具类接口
public interface HttpListener {
void success(String data);
void fail(String error);
}
public interface CartService {
@GET
Observable<ResponseBody> getCart(@Url String url);
}