Sometimes you might want to verify changes before they are broadcast.
The verified()
method (and the VerifiedState
class) facilitates such verifications by only accepting
changes from sub-states that are verified by given verification function.
For example, imagine you want a state whose value can only increase:
1linkimport { state, verified } from 'rxdeep';
2link
3linkconst ascending = verified(state(3),
4link change => !!change.value // --> not changing to `undefined
5link && change.trace.from < change.trace.to // --> we are changing to a larger value
6link)
7link
8linkascending.subscribe(console.log);
9link
10linkascending.value = 2; // --> rejected
11linkascending.value = 4; // --> accepted
12linkascending.value = 7; // --> accepted
13linkascending.value = 5; // --> rejected
14link
15link// Logs:
16link// > 3
17link// > 3 --> for the rejected 2
18link// > 4
19link// > 7
20link// > 7 --> for the rejected 5
info NOTE
You can also utilize
VerifiedState
class constructor instead ofverified()
function.
Each VerifiedState
(created with verified()
) is a child of State
with all
the same methods and attributes. The only difference is that it executeds the given verification
method on each incoming change, and if the change is rejected, it will not send it upstream,
but instead reverse the change and broadcast the reverse downstream so that sub-states correct
their corresponding values.