Skip to content

Commit 472e64e

Browse files
author
Nishanth Bhat
committed
feat: add passing data to background callback function
1 parent e0be82e commit 472e64e

File tree

16 files changed

+172
-135
lines changed

16 files changed

+172
-135
lines changed

README.md

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
1-
# react-native-background-sync
1+
# @rn-native-utils/background-sync
22

33
A React Native library for performing background data syncs in Android using Android's WorkManager.
44

55
## Installation
66

77
```sh
8-
npm install react-native-background-sync
8+
npm install @rn-native-utils/background-sync
99
```
1010

1111
or
1212

1313
```sh
14-
yarn add react-native-background-sync
14+
yarn add @rn-native-utils/background-sync
1515
```
1616

1717
## Supported Platforms
@@ -127,22 +127,22 @@ MINUTES = 'MINUTES',
127127

128128
## Types
129129
The BackgroundSchedulerParams type is used to configure the background task. Refer to the library's type definitions for the exact structure and available options.
130-
```ts
131-
export interface BackgroundSchedulerParams {
132-
taskKey: string;
133-
type: SchedulerTypes;
134-
maxRetryAttempts?: number;
135-
retryDelay?: number;
136-
taskTimeout?: number;
137-
allowedInForeground?: boolean;
138-
syncInterval?: number;
139-
syncIntervalType?: TimeUnits;
140-
syncFlexTime?: number;
141-
syncFlexTimeType?: TimeUnits;
142-
workerPolicy?: WorkerPolicy;
143-
}
144-
145-
```
130+
### BackgroundSchedulerParams
131+
132+
| Property | Type | Required | Description |
133+
|----------|------|----------|-------------|
134+
| taskKey | string | Yes | Unique identifier for the background task |
135+
| type | SchedulerTypes | Yes | Type of scheduler (PERIODIC or ONE_TIME) |
136+
| maxRetryAttempts | number | No | Maximum number of retry attempts if task fails |
137+
| retryDelay | number | No | Delay between retry attempts in milliseconds |
138+
| taskTimeout | number | No | Maximum time allowed for task execution |
139+
| allowedInForeground | boolean | No | Whether task can run while app is in foreground |
140+
| syncInterval | number | No | Interval between periodic syncs |
141+
| syncIntervalType | TimeUnits | No | Unit for syncInterval (SECOND, MINUTES, HOUR, DAY) |
142+
| syncFlexTime | number | No | Flex time window for periodic syncs |
143+
| syncFlexTimeType | TimeUnits | No | Unit for syncFlexTime |
144+
| workerPolicy | WorkerPolicy | No | Policy for handling existing workers
145+
| extras | Record<string, any> | No | Additional data to be passed to the background task |
146146

147147
## Error Handling
148148
All functions in this library throw errors if something goes wrong during execution. It's recommended to wrap calls to these functions in try-catch blocks for proper error handling.

android/src/main/java/com/backgroundsync/BackgroundSyncModule.kt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import com.facebook.react.bridge.ReactApplicationContext
1616
import com.facebook.react.bridge.ReactContextBaseJavaModule
1717
import com.facebook.react.bridge.ReactMethod
1818
import com.facebook.react.bridge.ReadableMap
19+
import com.facebook.react.bridge.ReadableType
1920

2021

2122
class BackgroundSyncModule(reactContext: ReactApplicationContext) :
@@ -86,7 +87,7 @@ class BackgroundSyncModule(reactContext: ReactApplicationContext) :
8687
if (isWorkCancelled(workManager,taskKey)) {
8788
promise.resolve(true)
8889
} else {
89-
promise.reject(false as String)
90+
promise.reject("CANCELLATION_ERROR", "Could not cancel task: $taskKey")
9091
}
9192
}
9293
catch (e:Exception){

android/src/main/java/com/backgroundsync/utils/WorkerUtils.kt

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
package com.backgroundsync.utils
22

3+
import android.util.Log
34
import androidx.work.Data
45
import androidx.work.ExistingPeriodicWorkPolicy
56
import androidx.work.WorkInfo
67
import androidx.work.WorkManager
78
import com.facebook.react.bridge.ReadableMap
9+
import com.facebook.react.bridge.ReadableType
810
import com.google.common.util.concurrent.ListenableFuture
911
import java.util.concurrent.ExecutionException
1012
import java.util.concurrent.TimeUnit
@@ -39,6 +41,38 @@ fun generateHeadlessConfig(params: ReadableMap): Data {
3941
val config = Data.Builder()
4042
.putString("taskKey", params.getString("taskKey"))
4143

44+
val extras = params.getMap("extras")
45+
extras?.let {
46+
val iterator = it.keySetIterator()
47+
while (iterator.hasNextKey()) {
48+
val key = iterator.nextKey()
49+
Log.d("TAG", "generateHeadlessConfig: $key")
50+
when (it.getType(key)) {
51+
ReadableType.String -> config.putString(key, it.getString(key))
52+
ReadableType.Number -> config.putDouble(key, it.getDouble(key))
53+
ReadableType.Boolean -> config.putBoolean(key, it.getBoolean(key))
54+
ReadableType.Null -> config.putString(key, null)
55+
ReadableType.Map -> {
56+
val nestedMap = it.getMap(key)?.toHashMap()
57+
nestedMap?.let { map ->
58+
config.putAll(map.mapKeys { "${key}_${it.key}" })
59+
}
60+
}
61+
ReadableType.Array -> {
62+
val array = it.getArray(key)?.toArrayList()
63+
array?.forEachIndexed { index, value ->
64+
when (value) {
65+
is String -> config.putString("${key}_$index", value)
66+
is Number -> config.putDouble("${key}_$index", value.toDouble())
67+
is Boolean -> config.putBoolean("${key}_$index", value)
68+
}
69+
}
70+
}
71+
}
72+
}
73+
}
74+
75+
4276
if(params.hasKey("maxRetryAttempts")) config.putInt("maxRetryAttempts", params.getInt("maxRetryAttempts"))
4377
if(params.hasKey("retryDelay")) config.putInt("retryDelay", params.getDouble("retryDelay").toInt())
4478
if(params.hasKey("taskTimeout")) config.putLong("taskTimeout", params.getDouble("taskTimeout").toLong())

example/src/App.tsx

Lines changed: 33 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import {
55
TimeUnits,
66
WorkerPolicy,
77
cancel,
8-
} from 'react-native-background-sync';
8+
} from '@rn-native-utils/workmanager';
99

1010
import BackgroundCall from './task-manager';
1111

@@ -14,11 +14,23 @@ export default function App() {
1414
const params = {
1515
taskKey: 'Onetime',
1616
type: SchedulerTypes.oneTime,
17+
extras: {
18+
hello: 'Hi',
19+
user: 'John',
20+
id: 123,
21+
data: {
22+
city: 'Pune',
23+
},
24+
},
1725
};
18-
const result = await schedule(params, async () => {
19-
BackgroundCall(params.taskKey);
20-
});
21-
console.log('Result:', result);
26+
try {
27+
const result = await schedule(params, async (data) =>
28+
BackgroundCall(data)
29+
);
30+
console.log('Result:', result);
31+
} catch (e) {
32+
console.error(e);
33+
}
2234
};
2335

2436
const schedulePeriodic = async () => {
@@ -30,16 +42,28 @@ export default function App() {
3042
syncFlexTime: 5,
3143
syncFlexTimeType: TimeUnits.MINUTES,
3244
workerPolicy: WorkerPolicy.KEEP,
45+
extras: {
46+
hello: 'Hi',
47+
user: 'John',
48+
id: 123,
49+
data: {
50+
city: 'Pune',
51+
},
52+
},
3353
};
34-
const result = await schedule(params, async () => {
35-
BackgroundCall(params.taskKey);
54+
const result = await schedule(params, async (data: any) => {
55+
BackgroundCall(data);
3656
});
3757
console.log('Result:', result);
3858
};
3959

4060
const cancelTask = async (taskKey: string) => {
41-
const response = await cancel(taskKey);
42-
Alert.alert(`Cancelled task for ${taskKey} : ${response}`);
61+
try {
62+
const response = await cancel(taskKey);
63+
Alert.alert(`Cancelled task for ${taskKey} : ${response}`);
64+
} catch (e) {
65+
console.error(e);
66+
}
4367
};
4468

4569
return (

example/src/task-manager.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
1-
const BackgroundCall = (name: string) => {
2-
console.log(`Calling in background for task: ${name}`);
1+
const BackgroundCall = (data?: any) => {
2+
console.log(
3+
`Calling in background for task: `,
4+
JSON.stringify(data, null, 2)
5+
);
36
};
47

58
export default BackgroundCall;

index.d.ts

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
export enum SchedulerTypes {
2+
periodic = 'PERIODIC',
3+
oneTime = 'ONE_TIME',
4+
}
5+
6+
export enum WorkerPolicy {
7+
KEEP = 'KEEP',
8+
REPLACE = 'REPLACE',
9+
UPDATE = 'UPDATE',
10+
}
11+
12+
export enum TimeUnits {
13+
HOUR = 'HOUR',
14+
DAY = 'DAY',
15+
SECOND = 'SECOND',
16+
MINUTES = 'MINUTES',
17+
}
18+
19+
export interface BackgroundSchedulerParams {
20+
taskKey: string;
21+
type: SchedulerTypes;
22+
maxRetryAttempts?: number;
23+
retryDelay?: number;
24+
taskTimeout?: number;
25+
allowedInForeground?: boolean;
26+
syncInterval?: number;
27+
syncIntervalType?: TimeUnits;
28+
syncFlexTime?: number;
29+
syncFlexTimeType?: TimeUnits;
30+
workerPolicy?: WorkerPolicy;
31+
extras: Record<string, unknown>;
32+
}
33+
34+
export function schedule(
35+
params: BackgroundSchedulerParams,
36+
callback: (data: string | Record<string, unknown> | boolean) => Promise<void>
37+
): Promise<boolean>;
38+
39+
export function cancel(taskKey: string): Promise<boolean>;
40+
41+
export function disableAppIgnoringBatteryOptimization(): boolean;
42+
43+
export type { BackgroundSchedulerParams };

ios/BackgroundSync-Bridging-Header.h

Lines changed: 0 additions & 2 deletions
This file was deleted.

ios/BackgroundSync.mm

Lines changed: 0 additions & 14 deletions
This file was deleted.

ios/BackgroundSync.swift

Lines changed: 0 additions & 8 deletions
This file was deleted.

package.json

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
2-
"name": "react-native-background-sync",
2+
"name": "@rn-native-utils/workmanager",
33
"version": "0.1.0",
44
"description": "Perform background data syncs in Android using Android's WorkManager",
55
"source": "./src/index.tsx",
@@ -18,12 +18,9 @@
1818
}
1919
},
2020
"files": [
21-
"src",
2221
"lib",
2322
"android",
24-
"ios",
2523
"cpp",
26-
"*.podspec",
2724
"!ios/build",
2825
"!android/build",
2926
"!android/gradle",

0 commit comments

Comments
 (0)