Skip to content

Commit

Permalink
retry failed calls
Browse files Browse the repository at this point in the history
  • Loading branch information
desperateCoder committed Sep 2, 2024
1 parent cbba1ae commit 5564fc3
Showing 1 changed file with 27 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@

public class RequestHelper {

private static final int RETRY_TIMES = 2;

@NonNull
private final ApiProvider apiProvider;

Expand All @@ -45,10 +47,33 @@ public <T> void request(@NonNull final Supplier<Call<T>> callProvider,
this.apiProvider.initSsoApi(callback::onError);
}

final var cb = new ResponseConsumer<>(this.apiProvider.getContext(), callback);
ExecutorServiceProvider.getLinkedBlockingQueueExecutor().submit(() -> callProvider.get().enqueue(cb));
final var call = callProvider.get();
final var cb = retryable(call, new ResponseConsumer<>(this.apiProvider.getContext(), callback));
ExecutorServiceProvider.getLinkedBlockingQueueExecutor().submit(() -> call.enqueue(cb));
}

private <T> Callback<T> retryable(final Call<T> originalCall, final ResponseConsumer<T> responseConsumer) {
return new Callback<T>() {
private int retries = RETRY_TIMES;

@Override
public void onResponse(@NonNull Call<T> call, @NonNull Response<T> response) {
responseConsumer.onResponse(call, response);
}

@Override
public void onFailure(@NonNull Call<T> call, @NonNull Throwable throwable) {
if (retries > 0) {
ExecutorServiceProvider.getLinkedBlockingQueueExecutor().submit(() -> originalCall.enqueue(this));
} else {
responseConsumer.onFailure(call, throwable);
}
retries--;
}
};
}


private static class ResponseConsumer<T> implements Callback<T> {
@NonNull
private final Context context;
Expand Down

0 comments on commit 5564fc3

Please sign in to comment.