Watching Auto Immutable Data
Any Auto Immutable instance communicates with its environment through its own Connection class (the consumer) instances.
The Connection's watch(...) method is a means by which a consumer can watch and directly react to updates occuring in the underlying immutable data.
Watchers registered through this method are notified of updates in the tick following that update. The consumer calling its connection set method may also obtain immediate notification by passing an onComplete second argument to the connection set method invocation.
A watcher callback function shares the same exact signature and arguments as the onComplete argument function.
Watcher can be dismissed through the Connection's unwatch(...) method. Ultimately, all watchers belonging to a connection are collectively dismissed when that connection disconnects.
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import AutoImmutable from 'auto-immutable';
import { expect, jest } from '@jest/globals';
jest.useFakeTimers();
const NUM_CONSUMERS = 5;
const aImmutable = new AutoImmutable({
a: {
b: {
c: 22
d: 60
},
x: 99
}
});
const createWatcher = ( myId, watchTask ) => {
return ( changes, changedPaths, originId ) => {
// only react to updates originated by others
myId !== originId && watchTask( changes, changedPaths );
};
};
const watchers = [];
const tasks = [];
const consumers = Array.from({ length: NUM_CONSUMERS }, () => {
const consumer = aImmutable.connect();
const task = jest.fn();
const watcher = createWatcher( consumer.instanceId, task );
consumer.watch( watcher );
watchers.push( watcher );
tasks.push( task );
return consumer;
} );
// Control Result
//---------------
tasks.forEach( t => expect( t ).not.toHaveBeenCalled() );
{
consumers[ 0 ].set({ a: { x: 1000 } });
jest.runAllTimers();
const [ task0, ...rest ] = tasks;
expect( task0 ).not.toHaveBeenCalled();
rest.forEach( t => {
expect( t ).toHaveBeenCalledTimes( 1 );
expect( t ).toHaveBeenCalledWith(
{ a: { x: 1000 } },
[[ 'a', 'x' ]],
consumers[ 0 ].instanceId
);
t.mockClear();
} );
}
{
consumer[ 2 ].set({ a: { b: { f: true } });
jest.runAllTimers();
let [ task0, task1, task2, ...rest ] = tasks;
rest = [ task0, task1, ...rest ]
expect( task2 ).not.toHaveBeenCalled();
rest.forEach( t => {
expect( t ).toHaveBeenCalledTimes( 1 );
expect( t ).toHaveBeenCalledWith(
{ a: { b: { f: true } },
[[ 'a', 'b', 'f' ]],
consumers[ 2 ].instanceId
);
t.mockClear();
} );
}
consumers.forEach(( consumer, i ) => consumer.unwatch( watchers[ i ] ));
consumers[ 1 ].set({ a: { b: { d: 100 } } });
jest.runAllTimers();
tasks.forEach( t => expect( t ).not.toHaveBeenCalled() );
jest.useRealTimers();