Skip to content

Commit 71885b3

Browse files
committed
fix: new responseOnMainThread option which allows running requests from worker
1 parent 460ef00 commit 71885b3

File tree

5 files changed

+53
-30
lines changed

5 files changed

+53
-30
lines changed

packages/https/platforms/android/java/com/nativescript/https/OkHttpResponse.java

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,12 @@
2323

2424
public class OkHttpResponse {
2525
private final static String TAG = "OkHttpResponse";
26-
private ResponseBody responseBody;
2726
static Handler mainHandler = null;
2827
static boolean RUN_ON_MAIN_THREAD = true;
2928
public static final int DOWNLOAD_CHUNK_SIZE = 2048; // Same as Okio Segment.SIZE
29+
30+
private ResponseBody responseBody;
31+
public boolean runOnMainThread = OkHttpResponse.RUN_ON_MAIN_THREAD;
3032
public OkHttpResponseProgressCallback progressCallback = null;
3133
public OkHttpResponseCloseCallback closeCallback = null;
3234

@@ -154,12 +156,12 @@ private static Handler getMainHandler() {
154156
return mainHandler;
155157
}
156158

157-
static void runProgressCallback(final OkHttpResponseProgressCallback progressCallback, final long current,
159+
private void runProgressCallback(final OkHttpResponseProgressCallback progressCallback, final long current,
158160
final long total) {
159161
if (progressCallback == null) {
160162
return;
161163
}
162-
if (RUN_ON_MAIN_THREAD) {
164+
if (runOnMainThread) {
163165
getMainHandler().post(new Runnable() {
164166
@Override
165167
public void run() {
@@ -171,11 +173,11 @@ public void run() {
171173
}
172174
}
173175

174-
static void runCloseCallback(final OkHttpResponseCloseCallback closeCallback) {
176+
private void runCloseCallback(final OkHttpResponseCloseCallback closeCallback) {
175177
if (closeCallback == null) {
176178
return;
177179
}
178-
if (RUN_ON_MAIN_THREAD) {
180+
if (runOnMainThread) {
179181

180182
getMainHandler().post(new Runnable() {
181183
@Override
@@ -188,7 +190,7 @@ public void run() {
188190
}
189191
}
190192

191-
static File responseBodyToFile(String filePath, OkHttpResponse response,
193+
private File responseBodyToFile(String filePath, OkHttpResponse response,
192194
OkHttpResponseProgressCallback progressCallback) throws Exception {
193195
BufferedInputStream input = null;
194196
OutputStream output = null;
@@ -239,7 +241,7 @@ private void closeResponseBody() {
239241
closeResponseBody(responseBody, closeCallback);
240242
}
241243

242-
private static void closeResponseBody(ResponseBody responseBody, OkHttpResponseCloseCallback closeCallback) {
244+
private void closeResponseBody(ResponseBody responseBody, OkHttpResponseCloseCallback closeCallback) {
243245
responseBody.close();
244246
runCloseCallback(closeCallback);
245247
}
@@ -284,7 +286,7 @@ public void run() {
284286
try {
285287
// Log.d(TAG, "toFileAsync run ");
286288
final File result = responseBodyToFile(filePath, fme, progressCallback);
287-
if (RUN_ON_MAIN_THREAD) {
289+
if (runOnMainThread) {
288290
getMainHandler().post(new Runnable() {
289291
@Override
290292
public void run() {
@@ -295,7 +297,7 @@ public void run() {
295297
callback.onFile(result);
296298
}
297299
} catch (final Exception exc) {
298-
if (RUN_ON_MAIN_THREAD) {
300+
if (runOnMainThread) {
299301
getMainHandler().post(new Runnable() {
300302
@Override
301303
public void run() {
@@ -333,7 +335,7 @@ public void toImageAsync(final OkHttpResponseAsyncCallback callback) {
333335
public void run() {
334336
try {
335337
final Bitmap result = responseBodyToBitmap(fme, progressCallback);
336-
if (RUN_ON_MAIN_THREAD) {
338+
if (runOnMainThread) {
337339
getMainHandler().post(new Runnable() {
338340
@Override
339341
public void run() {
@@ -344,7 +346,7 @@ public void run() {
344346
callback.onBitmap(result);
345347
}
346348
} catch (final Exception exc) {
347-
if (RUN_ON_MAIN_THREAD) {
349+
if (runOnMainThread) {
348350
getMainHandler().post(new Runnable() {
349351
@Override
350352
public void run() {
@@ -378,7 +380,7 @@ public void toByteArrayAsync(final OkHttpResponseAsyncCallback callback) {
378380
public void run() {
379381
try {
380382
final java.nio.ByteBuffer result = responseBodyToByteArray(fme);
381-
if (RUN_ON_MAIN_THREAD) {
383+
if (runOnMainThread) {
382384
getMainHandler().post(new Runnable() {
383385
@Override
384386
public void run() {
@@ -389,7 +391,7 @@ public void run() {
389391
callback.onByteArray(result);
390392
}
391393
} catch (final Exception exc) {
392-
if (RUN_ON_MAIN_THREAD) {
394+
if (runOnMainThread) {
393395
getMainHandler().post(new Runnable() {
394396
@Override
395397
public void run() {
@@ -426,7 +428,7 @@ public void asStringAsync(final OkHttpResponseAsyncCallback callback) {
426428
public void run() {
427429
try {
428430
final String result = responseBodyToString(fme);
429-
if (RUN_ON_MAIN_THREAD) {
431+
if (runOnMainThread) {
430432
getMainHandler().post(new Runnable() {
431433
@Override
432434
public void run() {
@@ -437,7 +439,7 @@ public void run() {
437439
callback.onString(result);
438440
}
439441
} catch (final Exception exc) {
440-
if (RUN_ON_MAIN_THREAD) {
442+
if (runOnMainThread) {
441443
getMainHandler().post(new Runnable() {
442444
@Override
443445
public void run() {

src/https/request.android.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -600,6 +600,9 @@ export function createRequest(opts: HttpsRequestOptions, useLegacy: boolean = tr
600600
};
601601
if (useLegacy) {
602602
const nResponse = new OkHttpResponse(responseBody);
603+
if (opts.responseOnMainThread === false) {
604+
nResponse.runOnMainThread = false;
605+
}
603606
if (opts.onProgress) {
604607
nResponse.progressCallback = new OkHttpResponse.OkHttpResponseProgressCallback({
605608
onProgress: opts.onProgress

src/https/request.d.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,11 @@ export interface HttpsRequestOptions extends HttpRequestOptions {
5959
*/
6060
onProgress?: (current: number, total: number) => void;
6161

62+
/**
63+
* default to true. Put to false to run response callback on current thread
64+
*/
65+
responseOnMainThread?: boolean;
66+
6267
cachePolicy?: CachePolicy;
6368

6469
/**

src/https/request.ios.ts

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,11 @@ function createNSRequest(url: string): NSMutableURLRequest {
106106

107107
class HttpsResponseLegacy implements IHttpsResponseLegacy {
108108
// private callback?: com.nativescript.https.OkhttpResponse.OkHttpResponseAsyncCallback;
109-
constructor(private data: NSDictionary<string, any> & NSData & NSArray<any>, public contentLength, private url: string) {}
109+
constructor(
110+
private data: NSDictionary<string, any> & NSData & NSArray<any>,
111+
public contentLength,
112+
private url: string
113+
) {}
110114
toArrayBufferAsync(): Promise<ArrayBuffer> {
111115
throw new Error('Method not implemented.');
112116
}
@@ -224,7 +228,7 @@ class HttpsResponseLegacy implements IHttpsResponseLegacy {
224228
} else {
225229
reject(new Error(`Cannot save file with path: ${destinationFilePath}.`));
226230
}
227-
})
231+
});
228232
this.file = r;
229233
return r;
230234
}
@@ -371,14 +375,17 @@ export function createRequest(opts: HttpsRequestOptions, useLegacy: boolean = tr
371375
);
372376
}
373377

374-
375378
manager.requestSerializer.timeoutInterval = opts.timeout ? opts.timeout : 10;
376379

377380
const progress = opts.onProgress
378381
? (progress: NSProgress) => {
379-
Utils.dispatchToMainThread(() => {
380-
opts.onProgress(progress.completedUnitCount, progress.totalUnitCount);
381-
});
382+
if (opts.responseOnMainThread === false) {
383+
opts.onProgress(progress.completedUnitCount, progress.totalUnitCount);
384+
} else {
385+
Utils.dispatchToMainThread(() => {
386+
opts.onProgress(progress.completedUnitCount, progress.totalUnitCount);
387+
});
388+
}
382389
}
383390
: null;
384391
let task: NSURLSessionDataTask;
@@ -466,20 +473,25 @@ export function createRequest(opts: HttpsRequestOptions, useLegacy: boolean = tr
466473
default:
467474
throw new Error('method_not_supported_multipart');
468475
}
469-
} else if (opts.method === 'PUT'){
476+
} else if (opts.method === 'PUT') {
470477
if (opts.body instanceof File) {
471478
const request = createNSRequest(opts.url);
472479
request.HTTPMethod = opts.method;
473-
Object.keys(heads).forEach(k => {
480+
Object.keys(heads).forEach((k) => {
474481
request.setValueForHTTPHeaderField(heads[k], k);
475482
});
476-
task = manager.uploadTaskWithRequestFromFileProgressCompletionHandler(request, NSURL.fileURLWithPath(opts.body.path), progress, (response: NSURLResponse, responseObject: any, error: NSError)=>{
477-
if (error) {
478-
failure(task, error);
479-
} else {
480-
success(task, responseObject);
483+
task = manager.uploadTaskWithRequestFromFileProgressCompletionHandler(
484+
request,
485+
NSURL.fileURLWithPath(opts.body.path),
486+
progress,
487+
(response: NSURLResponse, responseObject: any, error: NSError) => {
488+
if (error) {
489+
failure(task, error);
490+
} else {
491+
success(task, responseObject);
492+
}
481493
}
482-
});
494+
);
483495
task.resume();
484496
} else {
485497
let data: NSData;
@@ -493,7 +505,7 @@ export function createRequest(opts: HttpsRequestOptions, useLegacy: boolean = tr
493505
}
494506
const request = createNSRequest(opts.url);
495507
request.HTTPMethod = opts.method;
496-
Object.keys(heads).forEach(k => {
508+
Object.keys(heads).forEach((k) => {
497509
request.setValueForHTTPHeaderField(heads[k], k);
498510
});
499511
task = manager.uploadTaskWithRequestFromDataProgressCompletionHandler(request, data, progress, (response: NSURLResponse, responseObject: any, error: NSError) => {

src/https/typings/android.d.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ declare namespace com {
1313
export class OkHttpResponse {
1414
progressCallback: OkHttpResponse.OkHttpResponseProgressCallback;
1515
closeCallback: OkHttpResponse.OkHttpResponseCloseCallback;
16+
runOnMainThread: boolean;
1617
constructor(body: okhttp3.ResponseBody);
1718
contentLength(): number;
1819
cancel();

0 commit comments

Comments
 (0)