//Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
//RxJava
implementation 'io.reactivex.rxjava2:rxjava:2.1.12'
//Rxlife用于管理RxJava的订阅和解除
implementation 'com.trello.rxlifecycle2:rxlifecycle:2.2.1'
implementation 'com.trello.rxlifecycle2:rxlifecycle-components:2.2.1'
//RxAndroid
implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.9.0'
MainActivity中的使用
public class MainActivity extends AppCompatActivity implements MainContract.view {
MainPresenter mainPresenter;
PostModule pModule;
GetModule gModule;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainPresenter = new MainPresenter(this, this);
mainPresenter.getModule(0);
mainPresenter.getPostModule(0);
}
@Override
public void showPostModule(PostModule postModule) {
pModule = postModule;
}
@Override
public void showGetModule(GetModule getModule) {
gModule = getModule;
}
}
MainPresenter中的使用
public class MainPresenter implements MainContract.Presenter {
private MainContract.view view;
private Context context;
public MainPresenter(MainContract.view view, Context context) {
this.view = view;
this.context = context;
}
@Override
public void getPostModule(int id) {
RxHttp.getInstance().getPostModule(new HttpSubscriber(new SubscriberOnNextListener() {
@Override
public void onSuccess(PostModule postModule) {
view.showPostModule(postModule);
}
@Override
public void onError(int code, String errorMsg) {
}
}), id);
}
@Override
public void getModule(int id) {
RxHttp.getInstance().getModule(new HttpSubscriber(new SubscriberOnNextListener() {
@Override
public void onSuccess(GetModule getModule) {
view.showGetModule(getModule);
}
@Override
public void onError(int code, String errorMsg) {
}
}), id);
}
}
MainContract中的使用
public interface MainContract {
interface view {
void showPostModule(PostModule postModule);
void showGetModule(GetModule getModule);
}
interface Presenter {
void getPostModule(int id);
void getModule(int id);
}
}
准备的工具类:
运行时产生异常的原因
import android.text.TextUtils;
public class ApiException extends RuntimeException {
public static final int Code_TimeOut = 1000;
public static final int Code_UnConnected = 1001;
public static final int Code_MalformedJson = 1020;
public static final int Code_Default = 1003;
public static final String CONNECT_EXCEPTION = "网络连接异常,请检查您的网络状态";
public static final String SOCKET_TIMEOUT_EXCEPTION = "网络连接超时,请检查您的网络状态,稍后重试";
public static final String MALFORMED_JSON_EXCEPTION = "数据解析错误";
public ApiException(int resultCode, String msg) {
this(getApiExceptionMessage(resultCode, msg));
}
public ApiException(String detailMessage) {
super(detailMessage);
}
/**
* @param code
* @return
*/
private static String getApiExceptionMessage(int code, String msg) {
String message;
switch (code) {
case -1:
if (!TextUtils.isEmpty(msg)) {
message = msg;
} else {
message = "网络数据错误";
}
break;
default:
message = code + "#" + msg;
break;
}
return message;
}
}
这个类中写拼接的网址,参数和对应的参数类型
import com.example.rrm.module.GetModule;
import com.example.rrm.module.PostModule;
import io.reactivex.Observable;
import retrofit2.http.*;
public interface RxApiService {
/**
* POST
*/
@FormUrlEncoded
@POST("uri/post")
Observable getPostModule(@Field("id") int id);
/**
* GET
*/
@GET("uri/get")
Observable getModule(@Query("id") int id);
}
这个类中通过rxjava去调用接口
import com.example.rrm.module.GetModule;
import com.example.rrm.module.PostModule;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
public class RxHttp {
private RxHttp() {
}
private static final class RxHttpHolder {
private static final RxHttp Instance = new RxHttp();
}
public static RxHttp getInstance() {
return RxHttpHolder.Instance;
}
/**
* 获取post
*
* @param subscriber
* @param id
*/
public void getPostModule(Observer subscriber, int id) {
Observable observable = HttpManager.getRxService().getPostModule(id);
toSubscribe(observable, subscriber);
}
/**
* 获取get
*
* @param subscriber
* @param id
*/
public void getModule(Observer subscriber, int id) {
Observable observable = HttpManager.getRxService().getModule(id);
toSubscribe(observable, subscriber);
}
private void toSubscribe(Observable o, Observer s) {
o.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(s);
}
}
通过一个网络管理类封装retrofit并加入我们的初始网址
import android.util.Log;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import java.util.concurrent.TimeUnit;
public class HttpManager {
HttpManager() {
}
public static RxApiService getRxService() {
return RxServiceHolder.RX_SERVICE;
}
private static final class RxServiceHolder {
private static final RxApiService RX_SERVICE = RetrofitHolder.RETROFIT_CLIENT.create(RxApiService.class);
}
private static final class RetrofitHolder {
private static final Retrofit RETROFIT_CLIENT = new Retrofit.Builder()
.baseUrl("http://uri.api.com")//网址
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(OkHttpClientHolder.OK_HTTP_CLIENT)
.build();
}
private static final class OkHttpClientHolder {
private static final int TIME_OUT = 60;
private static final OkHttpClient OK_HTTP_CLIENT = new OkHttpClient
.Builder()
.connectTimeout(TIME_OUT, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
public void log(String message) {
Log.i("HttpManager", message);
}
}).setLevel(HttpLoggingInterceptor.Level.BODY))
.build();
}
}
接受调用接口锁获得的数据并传递给P层
import io.reactivex.disposables.Disposable;
import io.reactivex.exceptions.CompositeException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
public class HttpSubscriber implements io.reactivex.Observer {
private SubscriberOnNextListener mOnResultListener;
private Disposable mDisposable;
public HttpSubscriber(SubscriberOnNextListener listener) {
this.mOnResultListener = listener;
}
@Override
public void onSubscribe(Disposable d) {
mDisposable = d;
}
@Override
public void onNext(T t) {
if (mOnResultListener != null) {
mOnResultListener.onSuccess(t);
}
}
@Override
public void onError(Throwable e) {
if (e instanceof CompositeException) {
CompositeException compositeE = (CompositeException) e;
for (Throwable throwable : compositeE.getExceptions()) {
if (throwable instanceof SocketTimeoutException) {
mOnResultListener.onError(ApiException.Code_TimeOut, ApiException.SOCKET_TIMEOUT_EXCEPTION);
} else if (throwable instanceof ConnectException) {
mOnResultListener.onError(ApiException.Code_UnConnected, ApiException.CONNECT_EXCEPTION);
} else if (throwable instanceof UnknownHostException) {
mOnResultListener.onError(ApiException.Code_UnConnected, ApiException.CONNECT_EXCEPTION);
} else if (throwable instanceof com.google.gson.stream.MalformedJsonException) {
mOnResultListener.onError(ApiException.Code_MalformedJson, ApiException.MALFORMED_JSON_EXCEPTION);
}
}
} else {
String msg = e.getMessage();
int code;
if (msg != null && msg.contains("#")) {
code = Integer.parseInt(msg.split("#")[0]);
mOnResultListener.onError(code, msg.split("#")[1]);
} else {
code = ApiException.Code_Default;
if (msg != null && msg.contains("onNext called with null")) {
if (mOnResultListener != null) {
mOnResultListener.onSuccess(null);
}
} else {
mOnResultListener.onError(code, msg);
}
}
}
}
@Override
public void onComplete() {
}
public void unSubscribe() {
if (mDisposable != null && !mDisposable.isDisposed()) {
mDisposable.dispose();
}
}
}
public interface SubscriberOnNextListener {
void onSuccess(T t);
void onError(int code, String errorMsg);
}
这只是一层简单的封装,粘贴到demo中直接就能用,有想法的话可以自行优化其中的流程。