[FIX] Try fix Downloader cancel()

This commit is contained in:
Gravita 2021-08-02 02:51:38 +07:00
parent 9f44673809
commit 711413c52f

View file

@ -189,6 +189,7 @@ public static class ProgressTrackingBodyHandler<T> implements HttpResponse.BodyH
private final HttpResponse.BodyHandler<T> delegate; private final HttpResponse.BodyHandler<T> delegate;
private final DownloadCallback callback; private final DownloadCallback callback;
private ProgressTrackingBodySubscriber subscriber; private ProgressTrackingBodySubscriber subscriber;
private boolean isCanceled = false;
public ProgressTrackingBodyHandler(HttpResponse.BodyHandler<T> delegate, DownloadCallback callback) { public ProgressTrackingBodyHandler(HttpResponse.BodyHandler<T> delegate, DownloadCallback callback) {
this.delegate = delegate; this.delegate = delegate;
@ -198,10 +199,14 @@ public ProgressTrackingBodyHandler(HttpResponse.BodyHandler<T> delegate, Downloa
@Override @Override
public HttpResponse.BodySubscriber<T> apply(HttpResponse.ResponseInfo responseInfo) { public HttpResponse.BodySubscriber<T> apply(HttpResponse.ResponseInfo responseInfo) {
subscriber = new ProgressTrackingBodySubscriber(delegate.apply(responseInfo)); subscriber = new ProgressTrackingBodySubscriber(delegate.apply(responseInfo));
if (isCanceled) {
subscriber.cancel();
}
return subscriber; return subscriber;
} }
public void cancel() { public void cancel() {
isCanceled = true;
if (subscriber != null) { if (subscriber != null) {
subscriber.cancel(); subscriber.cancel();
} }
@ -210,6 +215,7 @@ public void cancel() {
private class ProgressTrackingBodySubscriber implements HttpResponse.BodySubscriber<T> { private class ProgressTrackingBodySubscriber implements HttpResponse.BodySubscriber<T> {
private final HttpResponse.BodySubscriber<T> delegate; private final HttpResponse.BodySubscriber<T> delegate;
private Flow.Subscription subscription; private Flow.Subscription subscription;
private boolean isCanceled = false;
public ProgressTrackingBodySubscriber(HttpResponse.BodySubscriber<T> delegate) { public ProgressTrackingBodySubscriber(HttpResponse.BodySubscriber<T> delegate) {
this.delegate = delegate; this.delegate = delegate;
@ -223,6 +229,9 @@ public CompletionStage<T> getBody() {
@Override @Override
public void onSubscribe(Flow.Subscription subscription) { public void onSubscribe(Flow.Subscription subscription) {
this.subscription = subscription; this.subscription = subscription;
if (isCanceled) {
subscription.cancel();
}
delegate.onSubscribe(subscription); delegate.onSubscribe(subscription);
} }
@ -247,6 +256,7 @@ public void onComplete() {
} }
public void cancel() { public void cancel() {
isCanceled = true;
if (subscription != null) { if (subscription != null) {
subscription.cancel(); subscription.cancel();
} }