-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
transaction.ts
38 lines (35 loc) · 1.14 KB
/
transaction.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
import {globalState} from "./globalstate";
import {runReactions} from "./reaction";
import {startBatch, endBatch} from "./observable";
import {isSpyEnabled, spyReportStart, spyReportEnd} from "./spy";
/**
* During a transaction no views are updated until the end of the transaction.
* The transaction will be run synchronously nonetheless.
* @param action a function that updates some reactive state
* @returns any value that was returned by the 'action' parameter.
*/
export function transaction<T>(action: () => T, thisArg = undefined, report = true): T {
transactionStart(((action as any).name) || "anonymous transaction", thisArg, report);
const res = action.call(thisArg);
transactionEnd(report);
return res;
}
export function transactionStart<T>(name: string, thisArg = undefined, report = true) {
startBatch();
globalState.inTransaction += 1;
if (report && isSpyEnabled()) {
spyReportStart({
type: "transaction",
target: thisArg,
name: name
});
}
}
export function transactionEnd<T>(report = true) {
if (--globalState.inTransaction === 0) {
runReactions();
}
if (report && isSpyEnabled())
spyReportEnd();
endBatch();
}