Skip to content

Commit

Permalink
#1657 sync issues: wait for call to complete before enquing more requ…
Browse files Browse the repository at this point in the history
…ests
  • Loading branch information
desperateCoder committed Nov 29, 2024
1 parent 22c717e commit 193647d
Showing 1 changed file with 19 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

import com.nextcloud.android.sso.exceptions.NextcloudHttpRequestFailedException;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

import it.niedermann.nextcloud.deck.DeckLog;
Expand Down Expand Up @@ -45,25 +47,38 @@ 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 CountDownLatch latch = new CountDownLatch(1);
final var cb = new ResponseConsumer<>(this.apiProvider.getContext(), callback, latch);
ExecutorServiceProvider.getLinkedBlockingQueueExecutor().submit(() -> {
callProvider.get().enqueue(cb);
try {
latch.await(20, TimeUnit.SECONDS);
} catch (InterruptedException e) {
DeckLog.logError(e);
}
});
DeckLog.log(DeckLog.Severity.DEBUG, "#Executor: " + ExecutorServiceProvider.getLinkedBlockingQueueExecutor().toString());
}

private static class ResponseConsumer<T> implements Callback<T> {
@NonNull
private final Context context;
@NonNull
private final ResponseCallback<T> callback;
@NonNull
private final CountDownLatch latch;

private ResponseConsumer(@NonNull Context context, @NonNull ResponseCallback<T> callback) {
private ResponseConsumer(@NonNull Context context, @NonNull ResponseCallback<T> callback, @NonNull CountDownLatch latch) {
this.context = context;
this.callback = callback;
this.latch = latch;
}

@Override
public void onResponse(@NonNull Call<T> call, Response<T> response) {
if (response.isSuccessful()) {
T responseObject = response.body();
latch.countDown();
callback.fillAccountIDs(responseObject);
callback.onResponse(responseObject, response.headers());
} else {
Expand Down Expand Up @@ -92,6 +107,7 @@ private RuntimeException buildCause(Response<T> response) {
@Override
public void onFailure(@NonNull Call<T> call, @NonNull Throwable t) {
DeckLog.logError(t);
latch.countDown();
callback.onError(ServerCommunicationErrorHandler.translateError(t));
}
}
Expand Down

0 comments on commit 193647d

Please sign in to comment.