MVP+retrofit+rxjava
2019-02-20 本文已影响0人
飞奔吧牛牛
以项目中的登陆模块为例演示MVP+retrofit+rxjava的使用
依赖
//网络库
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
//json解析
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.google.code.gson:gson:2.8.5'
//rx相关
implementation 'io.reactivex.rxjava2:rxjava:2.2.0'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'
封装网络请求
Api:
public interface ApiService {
@POST(ApiNameConstant.LOGIN)
Observable<UserInfo> doLogin(@Body RequestBody body);
}
Method:
public class HttpMethods {
private static final int DEFAULT_TIMEOUT = 20;//默认超时时间
private Retrofit mRetrofit;
private ApiService mService;
private static Gson gson;
private String baseUrl = ApiNameConstant.BASE_URL;
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
private HttpMethods() {
init(baseUrl);
}
private void init(String url) {
//创建OKHttpClient
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
mRetrofit = new Retrofit.Builder()
.client(client.build())
.addConverterFactory(GsonConverterFactory.create(buildGson()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(url)
.build();
mService = mRetrofit.create(ApiService.class);
}
private static Gson buildGson() {
if (gson == null) {
gson = new GsonBuilder()
.registerTypeAdapter(Integer.class, new IntegerDefault0Adapter())
.registerTypeAdapter(int.class, new IntegerDefault0Adapter())
.registerTypeAdapter(Double.class, new DoubleDefault0Adapter())
.registerTypeAdapter(double.class, new DoubleDefault0Adapter())
.registerTypeAdapter(Long.class, new LongDefault0Adapter())
.registerTypeAdapter(long.class, new LongDefault0Adapter())
.registerTypeAdapter(String.class, new StringDefault0Adapter())
.create();
}
return gson;
}
private static final HttpMethods INSTANCE = new HttpMethods();
public static HttpMethods getInstance() {
return INSTANCE;
}
/**
* 登录
*
* @param subscriber
* @param body
*/
public void login(ProgressSubscriber<UserInfo> subscriber, RequestBody body) {
mService.doLogin(body)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
}
}
ProgressSubscriber类来自于
https://github.com/zhou-you/RxEasyHttp实现带有进度的订阅
Model:
public interface ILoginModel {
void login(Context context, String userName, String password, OnLoginListener listener);
interface OnLoginListener {
void onLoginFail(String errorMsg);
void onLoginSuccess(String token, String userId);
}
}
public class LoginModel implements ILoginModel {
@Override
public void login(final Context context,String userName, String password, final OnLoginListener listener) {
RequestBody body = getBody(userName, password);
IProgressDialog dialog = UIUtils.getProgressDialog(context, "登录中...");
HttpMethods.getInstance().login(new ProgressSubscriber<UserInfo>(dialog,
true, true) {
@Override
public void onError(ApiException e) {
super.onError(e);
listener.onLoginFail(e.getMessage());
}
@Override
public void onNext(UserInfo loginResponseInfo) {
super.onNext(loginResponseInfo);
// TODO: 根据返回json格式,做非空判断和成功失败的判断
listener.onLoginSuccess(data.getToken(), data.getUserId());
listener.onLoginFail(e.getMessage());
}
}, body);
}
@NonNull
private RequestBody getBody(String userName, String password) {
LoginParams params = new LoginParams();
params.setLoginName(userName);
params.setLoginPwd(password);
params.setSourceCode(AppConstant.SOURCE_TIME_SHARE);
String json = JsonUtil.toJson(params,1);
return RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), json);
}
}
Presenter:调用Model中的方法,回调交给View来处理
public interface ILoginPresenter {
void login(String userName, String password);
}
public class LoginPresenter implements ILoginPresenter {
private Context context;
private ILoginView view;
private ILoginModel model;
public LoginPresenter(Context context, ILoginView view) {
this.context = context;
this.view = view;
model=new LoginModel();
}
@Override
public void login(String userName, String password) {
model.login(context, userName, password, new ILoginModel.OnLoginListener() {
@Override
public void onLoginFail(String errorMsg) {
view.onLoginFail(errorMsg);
}
@Override
public void onLoginSuccess(String token, String userId) {
view.onLoginSuccess(token,userId);
}
});
}
}
View:
public interface ILoginView {
void onLoginFail(String errorMsg);
void onLoginSuccess(String token, String userId);
}
使用:
public class LoginActivity extends BaseActivity implements ILoginView {
private ILoginPresenter presenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
presenter = new LoginPresenter(this, this);
}
@OnClick({R.id.btn_login})
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_login:
login();
break;
}
}
private void login() {
String phone = etPhone.getText().toString().trim();
String pwd = etPwd.getText().toString().trim();
...
检查手机号格式和密码格式
MD5加密密码
...
presenter.login(phone, pwd);
}
@Override
public void onLoginFail(String errorMsg) {
ToastUtil.showShortToast(errorMsg);
}
@Override
public void onLoginSuccess(String token, String userId) {
// TODO: 保存数据
finish();
}
}