Skip to content

Commit c7b8c93

Browse files
committed
fix(android): cancelRequest fix
1 parent 4f524b1 commit c7b8c93

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

src/https.android.ts

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -346,7 +346,10 @@ function getClient(reload: boolean = false, timeout: number = 10): okhttp3.OkHtt
346346
return Client;
347347
}
348348

349-
export function cancelRequest(tag: string, client: okhttp3.OkHttpClient) {
349+
export function cancelRequest(tag: string, client: okhttp3.OkHttpClient = runningClients[tag]) {
350+
if (!client) {
351+
return;
352+
}
350353
if (notClosedResponses[tag]) {
351354
notClosedResponses[tag].cancel();
352355
return;
@@ -382,6 +385,9 @@ let CALL_ID = 0;
382385
const notClosedResponses: {
383386
[k: string]: com.nativescript.https.OkHttpResponse;
384387
} = {};
388+
389+
const runningClients: { [k: string]: okhttp3.OkHttpClient } = {};
390+
385391
let OkHttpResponse: typeof com.nativescript.https.OkHttpResponse;
386392
export function createRequest(opts: Https.HttpsRequestOptions): Https.HttpsRequest {
387393
const client = getClient(false, opts.timeout);
@@ -458,7 +464,7 @@ export function createRequest(opts: Https.HttpsRequestOptions): Https.HttpsReque
458464
}
459465
const tag = opts.tag || `okhttp_request_${CALL_ID++}`;
460466
const call = client.newCall(request.tag(tag).build());
461-
467+
runningClients[tag] = client;
462468
// We have to allow networking on the main thread because larger responses will crash the app with an NetworkOnMainThreadException.
463469
// Note that it would probably be better to offload it to a Worker or (natively running) AsyncTask.
464470
// Also note that once set, this policy remains active until the app is killed.
@@ -472,6 +478,7 @@ export function createRequest(opts: Https.HttpsRequestOptions): Https.HttpsReque
472478
call.enqueue(
473479
new okhttp3.Callback({
474480
onResponse(call, response) {
481+
delete runningClients[tag];
475482
const responseBody = response.body();
476483
const message = response.message();
477484
const statusCode = response.code();
@@ -522,6 +529,7 @@ export function createRequest(opts: Https.HttpsRequestOptions): Https.HttpsReque
522529
}
523530
},
524531
onFailure(task, error) {
532+
delete runningClients[tag];
525533
reject(error);
526534
},
527535
})

0 commit comments

Comments
 (0)