-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReactInfGeneratorExample.tsx
65 lines (55 loc) · 1.58 KB
/
ReactInfGeneratorExample.tsx
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
import * as React from 'react';
import { useTask } from '@tynik/web-workers';
const ReactInfGeneratorExample = () => {
const [generatorTaskResults, setGeneratorTaskResults] = React.useState<{
result: number,
tookTime: number
}[]>([]);
const [
infinityGeneratorTask,
{
isRunning: simpleGeneratorTaskIsRunning,
isCompleted: simpleGeneratorTaskIsCompleted
}
] = useTask<never, number>(function* () {
let i = 0;
while (1) {
yield i++;
}
});
const runInfGeneratorTask = React.useCallback(async () => {
const gen = infinityGeneratorTask.run();
infinityGeneratorTask.whenNext(({ result, tookTime }) => {
setGeneratorTaskResults(genTaskResults =>
[...genTaskResults, { result, tookTime }]
);
// some waiting before run next generator cycle
setTimeout(gen.next, 1000);
});
// wait when generator is started
await gen.whenStarted;
// stop infinity generator in 5 secs.
setTimeout(gen.return, 5000);
}, [infinityGeneratorTask]);
React.useEffect(() => {
(
async () => {
if (!infinityGeneratorTask) {
return;
}
await runInfGeneratorTask();
}
)();
}, [infinityGeneratorTask]);
return (
<>
<p>Running: {simpleGeneratorTaskIsRunning ? 'Yes' : 'No'}</p>
<p>Completed: {simpleGeneratorTaskIsCompleted ? 'Yes' : 'No'}</p>
<p>Generator task result:</p>
<pre>
{generatorTaskResults.length ? JSON.stringify(generatorTaskResults, null, 2) : '?'}
</pre>
</>
);
};
export default ReactInfGeneratorExample;