Skip to content

Commit

Permalink
fix: new responseOnMainThread option which allows running requests …
Browse files Browse the repository at this point in the history
…from worker
  • Loading branch information
farfromrefug committed Jul 17, 2024
1 parent 460ef00 commit 71885b3
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 30 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,12 @@

public class OkHttpResponse {
private final static String TAG = "OkHttpResponse";
private ResponseBody responseBody;
static Handler mainHandler = null;
static boolean RUN_ON_MAIN_THREAD = true;
public static final int DOWNLOAD_CHUNK_SIZE = 2048; // Same as Okio Segment.SIZE

private ResponseBody responseBody;
public boolean runOnMainThread = OkHttpResponse.RUN_ON_MAIN_THREAD;
public OkHttpResponseProgressCallback progressCallback = null;
public OkHttpResponseCloseCallback closeCallback = null;

Expand Down Expand Up @@ -154,12 +156,12 @@ private static Handler getMainHandler() {
return mainHandler;
}

static void runProgressCallback(final OkHttpResponseProgressCallback progressCallback, final long current,
private void runProgressCallback(final OkHttpResponseProgressCallback progressCallback, final long current,
final long total) {
if (progressCallback == null) {
return;
}
if (RUN_ON_MAIN_THREAD) {
if (runOnMainThread) {
getMainHandler().post(new Runnable() {
@Override
public void run() {
Expand All @@ -171,11 +173,11 @@ public void run() {
}
}

static void runCloseCallback(final OkHttpResponseCloseCallback closeCallback) {
private void runCloseCallback(final OkHttpResponseCloseCallback closeCallback) {
if (closeCallback == null) {
return;
}
if (RUN_ON_MAIN_THREAD) {
if (runOnMainThread) {

getMainHandler().post(new Runnable() {
@Override
Expand All @@ -188,7 +190,7 @@ public void run() {
}
}

static File responseBodyToFile(String filePath, OkHttpResponse response,
private File responseBodyToFile(String filePath, OkHttpResponse response,
OkHttpResponseProgressCallback progressCallback) throws Exception {
BufferedInputStream input = null;
OutputStream output = null;
Expand Down Expand Up @@ -239,7 +241,7 @@ private void closeResponseBody() {
closeResponseBody(responseBody, closeCallback);
}

private static void closeResponseBody(ResponseBody responseBody, OkHttpResponseCloseCallback closeCallback) {
private void closeResponseBody(ResponseBody responseBody, OkHttpResponseCloseCallback closeCallback) {
responseBody.close();
runCloseCallback(closeCallback);
}
Expand Down Expand Up @@ -284,7 +286,7 @@ public void run() {
try {
// Log.d(TAG, "toFileAsync run ");
final File result = responseBodyToFile(filePath, fme, progressCallback);
if (RUN_ON_MAIN_THREAD) {
if (runOnMainThread) {
getMainHandler().post(new Runnable() {
@Override
public void run() {
Expand All @@ -295,7 +297,7 @@ public void run() {
callback.onFile(result);
}
} catch (final Exception exc) {
if (RUN_ON_MAIN_THREAD) {
if (runOnMainThread) {
getMainHandler().post(new Runnable() {
@Override
public void run() {
Expand Down Expand Up @@ -333,7 +335,7 @@ public void toImageAsync(final OkHttpResponseAsyncCallback callback) {
public void run() {
try {
final Bitmap result = responseBodyToBitmap(fme, progressCallback);
if (RUN_ON_MAIN_THREAD) {
if (runOnMainThread) {
getMainHandler().post(new Runnable() {
@Override
public void run() {
Expand All @@ -344,7 +346,7 @@ public void run() {
callback.onBitmap(result);
}
} catch (final Exception exc) {
if (RUN_ON_MAIN_THREAD) {
if (runOnMainThread) {
getMainHandler().post(new Runnable() {
@Override
public void run() {
Expand Down Expand Up @@ -378,7 +380,7 @@ public void toByteArrayAsync(final OkHttpResponseAsyncCallback callback) {
public void run() {
try {
final java.nio.ByteBuffer result = responseBodyToByteArray(fme);
if (RUN_ON_MAIN_THREAD) {
if (runOnMainThread) {
getMainHandler().post(new Runnable() {
@Override
public void run() {
Expand All @@ -389,7 +391,7 @@ public void run() {
callback.onByteArray(result);
}
} catch (final Exception exc) {
if (RUN_ON_MAIN_THREAD) {
if (runOnMainThread) {
getMainHandler().post(new Runnable() {
@Override
public void run() {
Expand Down Expand Up @@ -426,7 +428,7 @@ public void asStringAsync(final OkHttpResponseAsyncCallback callback) {
public void run() {
try {
final String result = responseBodyToString(fme);
if (RUN_ON_MAIN_THREAD) {
if (runOnMainThread) {
getMainHandler().post(new Runnable() {
@Override
public void run() {
Expand All @@ -437,7 +439,7 @@ public void run() {
callback.onString(result);
}
} catch (final Exception exc) {
if (RUN_ON_MAIN_THREAD) {
if (runOnMainThread) {
getMainHandler().post(new Runnable() {
@Override
public void run() {
Expand Down
3 changes: 3 additions & 0 deletions src/https/request.android.ts
Original file line number Diff line number Diff line change
Expand Up @@ -600,6 +600,9 @@ export function createRequest(opts: HttpsRequestOptions, useLegacy: boolean = tr
};
if (useLegacy) {
const nResponse = new OkHttpResponse(responseBody);
if (opts.responseOnMainThread === false) {
nResponse.runOnMainThread = false;
}
if (opts.onProgress) {
nResponse.progressCallback = new OkHttpResponse.OkHttpResponseProgressCallback({
onProgress: opts.onProgress
Expand Down
5 changes: 5 additions & 0 deletions src/https/request.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,11 @@ export interface HttpsRequestOptions extends HttpRequestOptions {
*/
onProgress?: (current: number, total: number) => void;

/**
* default to true. Put to false to run response callback on current thread
*/
responseOnMainThread?: boolean;

cachePolicy?: CachePolicy;

/**
Expand Down
42 changes: 27 additions & 15 deletions src/https/request.ios.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,11 @@ function createNSRequest(url: string): NSMutableURLRequest {

class HttpsResponseLegacy implements IHttpsResponseLegacy {
// private callback?: com.nativescript.https.OkhttpResponse.OkHttpResponseAsyncCallback;
constructor(private data: NSDictionary<string, any> & NSData & NSArray<any>, public contentLength, private url: string) {}
constructor(
private data: NSDictionary<string, any> & NSData & NSArray<any>,
public contentLength,
private url: string
) {}
toArrayBufferAsync(): Promise<ArrayBuffer> {
throw new Error('Method not implemented.');
}
Expand Down Expand Up @@ -224,7 +228,7 @@ class HttpsResponseLegacy implements IHttpsResponseLegacy {
} else {
reject(new Error(`Cannot save file with path: ${destinationFilePath}.`));
}
})
});
this.file = r;
return r;
}
Expand Down Expand Up @@ -371,14 +375,17 @@ export function createRequest(opts: HttpsRequestOptions, useLegacy: boolean = tr
);
}


manager.requestSerializer.timeoutInterval = opts.timeout ? opts.timeout : 10;

const progress = opts.onProgress
? (progress: NSProgress) => {
Utils.dispatchToMainThread(() => {
opts.onProgress(progress.completedUnitCount, progress.totalUnitCount);
});
if (opts.responseOnMainThread === false) {
opts.onProgress(progress.completedUnitCount, progress.totalUnitCount);
} else {
Utils.dispatchToMainThread(() => {
opts.onProgress(progress.completedUnitCount, progress.totalUnitCount);
});
}
}
: null;
let task: NSURLSessionDataTask;
Expand Down Expand Up @@ -466,20 +473,25 @@ export function createRequest(opts: HttpsRequestOptions, useLegacy: boolean = tr
default:
throw new Error('method_not_supported_multipart');
}
} else if (opts.method === 'PUT'){
} else if (opts.method === 'PUT') {
if (opts.body instanceof File) {
const request = createNSRequest(opts.url);
request.HTTPMethod = opts.method;
Object.keys(heads).forEach(k => {
Object.keys(heads).forEach((k) => {
request.setValueForHTTPHeaderField(heads[k], k);
});
task = manager.uploadTaskWithRequestFromFileProgressCompletionHandler(request, NSURL.fileURLWithPath(opts.body.path), progress, (response: NSURLResponse, responseObject: any, error: NSError)=>{
if (error) {
failure(task, error);
} else {
success(task, responseObject);
task = manager.uploadTaskWithRequestFromFileProgressCompletionHandler(
request,
NSURL.fileURLWithPath(opts.body.path),
progress,
(response: NSURLResponse, responseObject: any, error: NSError) => {
if (error) {
failure(task, error);
} else {
success(task, responseObject);
}
}
});
);
task.resume();
} else {
let data: NSData;
Expand All @@ -493,7 +505,7 @@ export function createRequest(opts: HttpsRequestOptions, useLegacy: boolean = tr
}
const request = createNSRequest(opts.url);
request.HTTPMethod = opts.method;
Object.keys(heads).forEach(k => {
Object.keys(heads).forEach((k) => {
request.setValueForHTTPHeaderField(heads[k], k);
});
task = manager.uploadTaskWithRequestFromDataProgressCompletionHandler(request, data, progress, (response: NSURLResponse, responseObject: any, error: NSError) => {
Expand Down
1 change: 1 addition & 0 deletions src/https/typings/android.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ declare namespace com {
export class OkHttpResponse {
progressCallback: OkHttpResponse.OkHttpResponseProgressCallback;
closeCallback: OkHttpResponse.OkHttpResponseCloseCallback;
runOnMainThread: boolean;
constructor(body: okhttp3.ResponseBody);
contentLength(): number;
cancel();
Expand Down

0 comments on commit 71885b3

Please sign in to comment.