在實際項目(Retrofit+RxJava框架)中,有時需要先登錄,獲取token后再去獲取用戶信息,此時我們使用flatmap操作符比較好。
在RESTResult對象里,包括請求返回的狀態:失敗還是成功,錯誤碼,User對象等等,我們根據接口先定義一個返回數據Response實體類:
public class Response<T> extends Entity { public boolean isSuccess() { return infoCode == 1; } public boolean isTokenExpired() { return infoCode == -1; } public int infoCode; public String message; public int size; public T data; }
邏輯處理:
- 登錄失敗,直接觸發onError;
- 登錄成功,根據獲得的token請求用戶信息接口最終調用subscribe的onNext事件;
如下代碼所示:
private void login(final String phone , final String password){ APIWrapper.getInstance().login(phone, password) .flatMap(new Func1<Response<TokenEntity>, Observable<Response<UserInfo>>>() { @Override public Observable<Response<UserInfo>> call(Response<TokenEntity> response) { if (response.isSuccess()) { TokenEntity tokenEntity = response.data; return APIWrapper.getInstance().getUserInfo(tokenEntity.token); } else { return Observable.error(new ApiException(response.message)); } } }) .compose(new RxHelper<Response<UserInfo>>(getString(R.string.wait_to_login_tip)).io_main(LoginActivity.this)) .subscribe(new RxSubscriber<Response<UserInfo>>(this,USER_LOGIN) { @Override public void _onNext(Response<UserInfo> response) { if (response.isSuccess()) { UserInfo userInfo = response.data; if (null != userInfo) { AppApplication.getInstance().saveUserInfo(userInfo); } finish(); } } @Override public void _onError(String msg) { ToastUtils.show(LoginActivity.this, msg); } }); }
根據上面代碼,登陸失敗后的處理很關鍵:
if (response.isSuccess()) { TokenEntity tokenEntity = response.data; return APIWrapper.getInstance().getUserInfo(tokenEntity.token); } else { return Observable.error(new ApiException(response.message));
無論何種原因造成的登陸失敗,都應跟用戶提示。
ApiException代碼:
public class ApiException extends RuntimeException { public static final int USER_NOT_EXIST = 100; public static final int WRONG_PASSWORD = 101; public static final int ERROR = 2001; public ApiException(int resultCode) { this(getApiExceptionMessage(resultCode)); } public ApiException(String detailMessage) { super(detailMessage); } /** * 由於服務器傳遞過來的錯誤信息直接給用戶看的話,用戶未必能夠理解 * 需要根據錯誤碼對錯誤信息進行一個轉換,在顯示給用戶 * @param code * @return */ private static String getApiExceptionMessage(int code){ String message ; switch (code) { case USER_NOT_EXIST: message = "該用戶不存在"; break; case WRONG_PASSWORD: message = "密碼錯誤"; break; default: message = "未知錯誤"; } return message; } }
通過RxJava的鏈式操作,結合恰當的操作符,不僅可以把正常的數據源發射給觀察者,同時也可以將錯誤異常數據源發射給觀察者,RxJava比想象中的更強大!
