RxJava + Retrofit - >用于API调用的BaseObservable用于集中响应处理

时间:2016-09-11 14:50:01

标签: android rx-java retrofit2 rx-android

我是RxJava的新手所以请原谅我,如果这听起来太新手了: - )。

截至目前,我有一个抽象的CallbackClass,它实现了Retofit Callback。在那里我捕获了Callback的“onResponse”和“onError”方法,并在最终转发到自定义实现的方法之前处理各种错误类型。 我还使用这个集中式类来进行请求/响应应用程序日志记录和其他内容。

例如:对于来自我的服务器的特定错误代码,我在响应正文中收到一个新的Auth令牌,刷新令牌然后clone.enqueue调用。 当然,我的服务器的响应还有其他一些全局行为。

当前解决方案(没有Rx):

    public abstract void onResponse(Call<T> call, Response<T> response, boolean isSuccess);

    public abstract void onFailure(Call<T> call, Response<T> response, Throwable t, boolean isTimeout);

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (_isCanceled) return;

        if (response != null && !response.isSuccessful()) {
            if (response.code() == "SomeCode" && retryCount < RETRY_LIMIT) {
                TokenResponseModel newToken = null;
                try {
                    newToken = new Gson().fromJson(new String(response.errorBody().bytes(), "UTF-8"), TokenResponseModel.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                    SomeClass.token = newToken.token;
                    retryCount++;
                    call.clone().enqueue(this);
                    return;
                }
            }
        } else {
            onResponse(call, response, true);
            removeFinishedRequest();
            return;
        }

        onFailure(call, response, null, false);
        removeFinishedRequest();
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        if (_isCanceled) return;

        if (t instanceof UnknownHostException)
            if (eventBus != null)
                eventBus.post(new NoConnectionErrorEvent());

        onFailure(call, null, t, false);
        removeFinishedRequest();
    }

我的问题是:在最终链接(或重试)回订阅者方法之前,有没有办法让这种集中式响应处理行为?

我发现这两个链接都有一个很好的起点,但不是一个具体的解决方案。任何帮助都将非常感激。

Forcing request retry after custom API exceptions in RxJava

Retrofit 2 and RxJava error handling operators

3 个答案:

答案 0 :(得分:7)

您提供的两个链接是一个非常好的起点,我用它来构建解决方案以应对意外

  • 网络错误有时是由于暂时缺少网络连接,或者切换到低吞吐量网络标准,如EDGE,导致SocketTimeoutException
  • 服务器错误 - &gt;有时由于服务器过载而发生

我已覆盖CallAdapter.Factory来处理错误并对其作出适当的反应。

  1. 从您找到的solution

  2. 导入RetryWithDelayIf
  3. 覆盖CallAdapter.Factory以处理错误:

    public class RxCallAdapterFactoryWithErrorHandling extends CallAdapter.Factory {
        private final RxJavaCallAdapterFactory original;
    
        public RxCallAdapterFactoryWithErrorHandling() {
            original = RxJavaCallAdapterFactory.create();
        }
    
        @Override
        public CallAdapter<?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
            return new RxCallAdapterWrapper(retrofit, original.get(returnType, annotations, retrofit));
        }
    
        public class RxCallAdapterWrapper implements CallAdapter<Observable<?>> {
            private final Retrofit retrofit;
            private final CallAdapter<?> wrapped;
    
            public RxCallAdapterWrapper(Retrofit retrofit, CallAdapter<?> wrapped) {
                this.retrofit = retrofit;
                this.wrapped = wrapped;
            }
    
            @Override
            public Type responseType() {
                return wrapped.responseType();
            }
    
            @SuppressWarnings("unchecked")
            @Override
            public <R> Observable<?> adapt(final Call<R> call) {
                return ((Observable) wrapped.adapt(call)).onErrorResumeNext(new Func1<Throwable, Observable>() {
                    @Override
                    public Observable call(Throwable throwable) {
                        Throwable returnThrowable = throwable;
                        if (throwable instanceof HttpException) {
                            HttpException httpException = (HttpException) throwable;
                            returnThrowable = httpException;
                            int responseCode = httpException.response().code();
                            if (NetworkUtils.isClientError(responseCode)) {
                                returnThrowable = new HttpClientException(throwable);
                            }
                            if (NetworkUtils.isServerError(responseCode)) {
                                returnThrowable = new HttpServerException(throwable);
                            }
                        }
    
                        if (throwable instanceof UnknownHostException) {
                            returnThrowable = throwable;
                        }
    
                        return Observable.error(returnThrowable);
                    }
                }).retryWhen(new RetryWithDelayIf(3, DateUtils.SECOND_IN_MILLIS, new Func1<Throwable, Boolean>() {
                    @Override
                    public Boolean call(Throwable throwable) {
                        return throwable instanceof HttpServerException
                                || throwable instanceof SocketTimeoutException
                                || throwable instanceof UnknownHostException;
                    }
                }));
            }
        }
    }
    

    HttpServerException只是一个自定义例外。

  4. Retrofit.Builder

    中使用它
    Retrofit retrofit = new Retrofit.Builder()
            .addCallAdapterFactory(new RxCallAdapterFactoryWithErrorHandling())
            .build();
    
  5. 额外:如果您希望解析来自API的错误(不会调用UnknownHostExceptionHttpExceptionMalformedJsonException或其他错误。)您需要覆盖Factory并在构建Retrofit实例期间使用自定义的一个。解析响应并检查它是否包含错误。如果是,则抛出错误并在上述方法中处理错误。

答案 1 :(得分:0)

您是否考虑过使用rxjava适配器进行改造? https://mvnrepository.com/artifact/com.squareup.retrofit2/adapter-rxjava/2.1.0 在您的gradle文件中添加

compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'

这是改装的界面

public interface Service {
@GET("userauth/login?")
Observable<LoginResponse> getLogin(
        @Query("v") String version,
        @Query("username") String username,
        @Query("password") String password);
}

这是我的实施

Service.getLogin(
            VERSION,
            "username",
            "password")
            .subscribe(new Subscriber<LoginResponse>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onNext(LoginResponse loginResponse) {

                }
            });

请注意我正在使用gson转换器工厂来解析我的响应,所以我得到了一个pojo(Plain Ole Java Object)。

答案 2 :(得分:0)

了解如何做到这一点。  这是api调用并传递Request模型和响应模型。

public interface RestService {
//SEARCH_USER
@POST(SEARCH_USER_API_LINK)
Observable<SearchUserResponse> getSearchUser(@Body SearchUserRequest getSearchUserRequest);
}

这是改装电话,我使用了retrofit2

public RestService getRestService() {

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(ApiConstants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .client(getOkHttpClient())
            .build();

    return retrofit.create(RestService.class);
}

//get OkHttp instance
@Singleton
@Provides
public OkHttpClient getOkHttpClient() {

    HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
    httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.interceptors().add(httpLoggingInterceptor);
    builder.readTimeout(60, TimeUnit.SECONDS);
    builder.connectTimeout(60, TimeUnit.SECONDS);
    return builder.build();
}

这是api电话,在你的活动中称呼它。

@Inject
Scheduler mMainThread;
@Inject
Scheduler mNewThread;

 //getSearchUser api method
public void getSearchUser(String user_id, String username) {

    SearchUserRequest searchUserRequest = new SearchUserRequest(user_id, username);

    mObjectRestService.getSearchUser(searchUserRequest).
            subscribeOn(mNewThread).
            observeOn(mMainThread).
            subscribe(searchUserResponse -> {
                Timber.e("searchUserResponse :" + searchUserResponse.getResponse().getResult());
                if (isViewAttached()) {
                    getMvpView().hideProgress();
                    if (searchUserResponse.getResponse().getResult() == ApiConstants.STATUS_SUCCESS) {

                    } else {

                    }
                }
            }, throwable -> {
                if (isViewAttached()) {

                }
            });
}

希望这会对你有所帮助。