Skip to content

Commit dc971a3

Browse files
lexsMartin Konicek
authored andcommitted
Add GuardedResultAsyncTask
Reviewed By: andreicoman11 Differential Revision: D2679459 fb-gh-sync-id: 8a9ec170ce76bbc3340c9e8872e19b78ae5a5c2d
1 parent ed6f4a5 commit dc971a3

2 files changed

Lines changed: 45 additions & 3 deletions

File tree

ReactAndroid/src/main/java/com/facebook/react/bridge/GuardedAsyncTask.java

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,8 @@
1616
* handled by the {@link com.facebook.react.bridge.NativeModuleCallExceptionHandler} registered if
1717
* the app is in dev mode.
1818
*
19-
* This class doesn't allow doInBackground to return a results. This is mostly because when this
20-
* class was written that functionality wasn't used and it would require some extra code to make
21-
* work correctly with caught exceptions. Don't let that stop you from adding it if you need it :)
19+
* This class doesn't allow doInBackground to return a results. If you need this
20+
* use GuardedResultAsyncTask instead.
2221
*/
2322
public abstract class GuardedAsyncTask<Params, Progress>
2423
extends AsyncTask<Params, Progress, Void> {
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Copyright 2004-present Facebook. All Rights Reserved.
2+
3+
package com.facebook.react.bridge;
4+
5+
import android.os.AsyncTask;
6+
7+
/**
8+
* Abstract base for a AsyncTask with result support that should have any RuntimeExceptions it
9+
* throws handled by the {@link com.facebook.react.bridge.NativeModuleCallExceptionHandler}
10+
* registered if the app is in dev mode.
11+
*/
12+
public abstract class GuardedResultAsyncTask<Result>
13+
extends AsyncTask<Void, Void, Result> {
14+
15+
private final ReactContext mReactContext;
16+
17+
protected GuardedResultAsyncTask(ReactContext reactContext) {
18+
mReactContext = reactContext;
19+
}
20+
21+
@Override
22+
protected final Result doInBackground(Void... params) {
23+
try {
24+
return doInBackgroundGuarded();
25+
} catch (RuntimeException e) {
26+
mReactContext.handleException(e);
27+
throw e;
28+
}
29+
}
30+
31+
@Override
32+
protected final void onPostExecute(Result result) {
33+
try {
34+
onPostExecuteGuarded(result);
35+
} catch (RuntimeException e) {
36+
mReactContext.handleException(e);
37+
}
38+
}
39+
40+
protected abstract Result doInBackgroundGuarded();
41+
protected abstract void onPostExecuteGuarded(Result result);
42+
43+
}

0 commit comments

Comments
 (0)