-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathcreateReactionCleanupTrackingUsingFinalizationRegister.ts
57 lines (51 loc) · 2.21 KB
/
createReactionCleanupTrackingUsingFinalizationRegister.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
import { FinalizationRegistry as FinalizationRegistryMaybeUndefined } from "./FinalizationRegistryWrapper"
import { Reaction } from "mobx"
import {
ReactionCleanupTracking,
IReactionTracking,
createTrackingData
} from "./reactionCleanupTrackingCommon"
/**
* FinalizationRegistry-based uncommitted reaction cleanup
*/
export function createReactionCleanupTrackingUsingFinalizationRegister(
FinalizationRegistry: NonNullable<typeof FinalizationRegistryMaybeUndefined>
): ReactionCleanupTracking {
const cleanupTokenToReactionTrackingMap = new Map<number, IReactionTracking>()
let globalCleanupTokensCounter = 1
const registry = new FinalizationRegistry(function cleanupFunction(token: number) {
const trackedReaction = cleanupTokenToReactionTrackingMap.get(token)
if (trackedReaction) {
trackedReaction.reaction.dispose()
cleanupTokenToReactionTrackingMap.delete(token)
}
})
return {
addReactionToTrack(
reactionTrackingRef: React.MutableRefObject<IReactionTracking | null>,
reaction: Reaction,
objectRetainedByReact: object
) {
const token = globalCleanupTokensCounter++
registry.register(objectRetainedByReact, token, reactionTrackingRef)
reactionTrackingRef.current = createTrackingData(reaction)
reactionTrackingRef.current.finalizationRegistryCleanupToken = token
cleanupTokenToReactionTrackingMap.set(token, reactionTrackingRef.current)
return reactionTrackingRef.current
},
recordReactionAsCommitted(reactionRef: React.MutableRefObject<IReactionTracking | null>) {
registry.unregister(reactionRef)
if (reactionRef.current && reactionRef.current.finalizationRegistryCleanupToken) {
cleanupTokenToReactionTrackingMap.delete(
reactionRef.current.finalizationRegistryCleanupToken
)
}
},
forceCleanupTimerToRunNowForTests() {
// When FinalizationRegistry in use, this this is no-op
},
resetCleanupScheduleForTests() {
// When FinalizationRegistry in use, this this is no-op
}
}
}