@exodus/atoms 5.5.0 → 5.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@exodus/atoms",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.6.0",
|
|
4
4
|
"main": "src/index.js",
|
|
5
5
|
"description": "Abstraction for encapsulating a piece of data behind a simple unified interface: get, set, observe",
|
|
6
6
|
"author": "Exodus Movement Inc.",
|
|
@@ -36,5 +36,5 @@
|
|
|
36
36
|
"eslint": "^8.44.0",
|
|
37
37
|
"jest": "^29.1.2"
|
|
38
38
|
},
|
|
39
|
-
"gitHead": "
|
|
39
|
+
"gitHead": "aec5804ed663dec0767599dde6208d8487ab07f7"
|
|
40
40
|
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import makeConcurrent from 'make-concurrent'
|
|
2
|
+
import createInMemoryAtom from '../factories/memory'
|
|
3
|
+
|
|
4
|
+
const optimisticNotifier = (atom) => {
|
|
5
|
+
const memoryAtom = createInMemoryAtom()
|
|
6
|
+
|
|
7
|
+
const set = makeConcurrent(async (newValue) => {
|
|
8
|
+
let previous
|
|
9
|
+
await memoryAtom.set((previousValue) => {
|
|
10
|
+
previous = previousValue
|
|
11
|
+
return newValue
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
atom
|
|
15
|
+
.set(newValue)
|
|
16
|
+
// only revert in case the value hasn't changed in the meanwhile
|
|
17
|
+
.catch(() => memoryAtom.set((value) => (value === newValue ? previous : value)))
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
let unsubscribeSource
|
|
21
|
+
let subscribers = 0
|
|
22
|
+
|
|
23
|
+
const maybeUnsubscribeSource = () => {
|
|
24
|
+
subscribers -= 1
|
|
25
|
+
if (subscribers > 0) return
|
|
26
|
+
unsubscribeSource()
|
|
27
|
+
unsubscribeSource = undefined
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const observe = (callback) => {
|
|
31
|
+
if (subscribers === 0) {
|
|
32
|
+
unsubscribeSource = atom.observe(set)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
subscribers += 1
|
|
36
|
+
const unsubscribe = memoryAtom.observe(callback)
|
|
37
|
+
|
|
38
|
+
return () => {
|
|
39
|
+
unsubscribe()
|
|
40
|
+
maybeUnsubscribeSource()
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const get = async () => {
|
|
45
|
+
if (subscribers === 0) {
|
|
46
|
+
return atom.get()
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return memoryAtom.get()
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return {
|
|
53
|
+
...memoryAtom,
|
|
54
|
+
set,
|
|
55
|
+
get,
|
|
56
|
+
observe,
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export default optimisticNotifier
|