-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBackgroundQueue.ts
74 lines (72 loc) · 1.88 KB
/
BackgroundQueue.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import queueFactory from 'react-native-queue-asyncstorage';
import {
BackgroundQueueErrorEnum,
KeyValuePairs,
QueueState,
} from '~/Queue/types';
export class BackgroundQueue {
private queueState: QueueState = 'inactive';
private queue: any | null = null;
constructor() {
this.initializeQueue();
}
async initializeQueue() {
this.queue = await queueFactory();
return Promise.resolve(true);
}
startQueue() {
// Start queue to process any jobs that hadn't finished when app was last closed.
this.queue.start();
}
addWorker(
workerName: string,
worker: (id: number, payload: KeyValuePairs) => void,
): Promise<any> {
return new Promise((resolve, reject) => {
if (!this.checkQueueInitialized()) {
return reject({
workerName: workerName,
error: BackgroundQueueErrorEnum.add_worker_failed,
});
}
this.queue.addWorker(
workerName,
async (id: number, payload: KeyValuePairs) => {
try {
await worker(id, payload);
await new Promise(resolve => {
setTimeout(() => {
resolve({workerId: id, workerPayload: payload});
}, 5);
});
} catch (e) {
reject({
workerId: id,
workerPayload: payload,
error: BackgroundQueueErrorEnum.worker_execute_error,
});
}
},
);
});
}
createJob(jobName: string, payload: KeyValuePairs) {
if (!this.checkQueueInitialized()) {
return;
}
this.queue.createJob(jobName, payload);
}
getQueueState(): string {
return this.queueState;
}
setQueueState(state: QueueState): void {
this.queueState = state;
}
resetQueue(): void {
this.initializeQueue();
this.startQueue();
}
checkQueueInitialized(): boolean {
return this.queue !== null;
}
}