use of com.github.natanbc.reliqua.limiter.RateLimiter in project Ree6 by Ree6-Applications.
the class PendingRequest method async.
/**
* Execute this request asynchronously, calling the appropriate callback when it's done.
*
* @param onSuccess Called when this request completes successfully.
* @param onError Called when there's an error executing the request or parsing the response.
*/
public void async(@Nullable Consumer<T> onSuccess, @Nullable Consumer<RequestException> onError) {
StackTraceElement[] callSite = api.isTrackingCallSites() ? Thread.currentThread().getStackTrace() : null;
if (onSuccess == null)
onSuccess = v -> {
};
if (onError == null)
onError = Throwable::printStackTrace;
Consumer<T> finalOnSuccess = onSuccess;
Consumer<RequestException> finalOnError = onError;
Runnable r = () -> api.getClient().newCall(httpRequest).enqueue(new Callback() {
@Override
public void onFailure(@Nonnull Call call, @Nonnull IOException e) {
finalOnError.accept(new RequestException(e, callSite));
}
@Override
public void onResponse(@Nonnull Call call, @Nonnull Response response) {
try {
ResponseBody body = response.body();
if (!statusCodeValidator.test(response.code())) {
try {
onError(new RequestContext<>(callSite, finalOnSuccess, finalOnError, response));
} finally {
if (body != null) {
body.close();
}
}
return;
}
try {
finalOnSuccess.accept(onSuccess(response));
} finally {
if (body != null) {
body.close();
}
}
} catch (RequestException e) {
finalOnError.accept(e);
} catch (Exception e) {
finalOnError.accept(new RequestException(e, callSite));
}
}
});
if (rateLimiter == null) {
r.run();
} else {
rateLimiter.queue(r);
}
}
Aggregations