1 | import { FinalizationRegistry as FinalizationRegistryMaybeUndefined } from "./FinalizationRegistryWrapper"
|
2 | import { Reaction } from "mobx"
|
3 | import {
|
4 | ReactionCleanupTracking,
|
5 | IReactionTracking,
|
6 | createTrackingData
|
7 | } from "./reactionCleanupTrackingCommon"
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | export function createReactionCleanupTrackingUsingFinalizationRegister(
|
13 | FinalizationRegistry: NonNullable<typeof FinalizationRegistryMaybeUndefined>
|
14 | ): ReactionCleanupTracking {
|
15 | const cleanupTokenToReactionTrackingMap = new Map<number, IReactionTracking>()
|
16 | let globalCleanupTokensCounter = 1
|
17 |
|
18 | const registry = new FinalizationRegistry(function cleanupFunction(token: number) {
|
19 | const trackedReaction = cleanupTokenToReactionTrackingMap.get(token)
|
20 | if (trackedReaction) {
|
21 | trackedReaction.reaction.dispose()
|
22 | cleanupTokenToReactionTrackingMap.delete(token)
|
23 | }
|
24 | })
|
25 |
|
26 | return {
|
27 | addReactionToTrack(
|
28 | reactionTrackingRef: React.MutableRefObject<IReactionTracking | null>,
|
29 | reaction: Reaction,
|
30 | objectRetainedByReact: object
|
31 | ) {
|
32 | const token = globalCleanupTokensCounter++
|
33 |
|
34 | registry.register(objectRetainedByReact, token, reactionTrackingRef)
|
35 | reactionTrackingRef.current = createTrackingData(reaction)
|
36 | reactionTrackingRef.current.finalizationRegistryCleanupToken = token
|
37 | cleanupTokenToReactionTrackingMap.set(token, reactionTrackingRef.current)
|
38 |
|
39 | return reactionTrackingRef.current
|
40 | },
|
41 | recordReactionAsCommitted(reactionRef: React.MutableRefObject<IReactionTracking | null>) {
|
42 | registry.unregister(reactionRef)
|
43 |
|
44 | if (reactionRef.current && reactionRef.current.finalizationRegistryCleanupToken) {
|
45 | cleanupTokenToReactionTrackingMap.delete(
|
46 | reactionRef.current.finalizationRegistryCleanupToken
|
47 | )
|
48 | }
|
49 | },
|
50 | forceCleanupTimerToRunNowForTests() {
|
51 |
|
52 | },
|
53 | resetCleanupScheduleForTests() {
|
54 |
|
55 | }
|
56 | }
|
57 | }
|