This can help you. I am implementing an RxJava2 statement to handle an APiError. I used the elevator operator.
See an example.
public final class ApiClient implements ApiClientInterface { ... @NonNull @Override public Observable<ActivateResponse> activate(String email, EmailData emailLinkData) { return myApiService.activate(email, emailData) .lift(getApiErrorTransformer()) .subscribeOn(Schedulers.io()); } private <T>ApiErrorOperator<T> getApiErrorTransformer() { return new ApiErrorOperator<>(gson, networkService); } }
And then you can find the user statement
public final class ApiErrorOperator<T> implements ObservableOperator<T, T> { private static final String TAG = "ApiErrorOperator"; private final Gson gson; private final NetworkService networkService; public ApiErrorOperator(@NonNull Gson gson, @NonNull NetworkService networkService) { this.gson = gson; this.networkService = networkService; } @Override public Observer<? super T> apply(Observer<? super T> observer) throws Exception { return new Observer<T>() { @Override public void onSubscribe(Disposable d) { observer.onSubscribe(d); } @Override public void onNext(T value) { observer.onNext(value); } @Override public void onError(Throwable e) { Log.e(TAG, "onError", e); if (e instanceof HttpException) { try { HttpException error = (HttpException) e; Response response = error.response(); String errorBody = response.errorBody().string(); ErrorResponse errorResponse = gson.fromJson(errorBody.trim(), ErrorResponse.class); ApiException exception = new ApiException(errorResponse, response); observer.onError(exception); } catch (IOException exception) { observer.onError(exception); } } else if (!networkService.isNetworkAvailable()) { observer.onError(new NetworkException(ErrorResponse.builder() .setErrorCode("") .setDescription("No Network Connection Error") .build())); } else { observer.onError(e); } } @Override public void onComplete() { observer.onComplete(); } }; } }
source share