-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReactSimpleGeneratorExample.tsx
62 lines (51 loc) · 1.48 KB
/
ReactSimpleGeneratorExample.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
import * as React from 'react';
import { useTask } from '@tynik/web-workers';
const ReactSimpleGeneratorExample = () => {
const [generatorTaskResults, setGeneratorTaskResults] = React.useState<{
result: number,
tookTime: number
}[]>([]);
const [
simpleGeneratorTask,
{
isRunning: simpleGeneratorTaskIsRunning,
isCompleted: simpleGeneratorTaskIsCompleted
}
] = useTask<never, number>(
function* () {
yield 1;
// fibonacci calculation for some waiting
fibonacci(37);
yield 2;
fibonacci(38);
yield 3;
function fibonacci(num) {
if (num <= 1) return 1;
return fibonacci(num - 1) + fibonacci(num - 2);
}
});
React.useEffect(() => {
if (!simpleGeneratorTask) {
return;
}
const gen = simpleGeneratorTask.run();
simpleGeneratorTask.whenNext(({ result, tookTime }) => {
setGeneratorTaskResults(genTaskResults =>
[...genTaskResults, { result, tookTime }]
);
// some waiting before run next generator cycle
setTimeout(() => gen.next(), 1000);
});
}, [simpleGeneratorTask]);
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 ReactSimpleGeneratorExample;