aboutsummaryrefslogtreecommitdiffstats
path: root/app/scripts/lib
diff options
context:
space:
mode:
authorbitpshr <mail@bitpshr.net>2018-04-13 11:26:50 +0800
committerbitpshr <mail@bitpshr.net>2018-04-13 22:20:44 +0800
commit4780f825b1bfb33f03c60133f293b122b8b43be4 (patch)
treedd597859b1979f7175a06dc305dac1e229c70244 /app/scripts/lib
parent29dab1e9e00c1c1e6ad834026df51b2839d3171d (diff)
downloadtangerine-wallet-browser-4780f825b1bfb33f03c60133f293b122b8b43be4.tar
tangerine-wallet-browser-4780f825b1bfb33f03c60133f293b122b8b43be4.tar.gz
tangerine-wallet-browser-4780f825b1bfb33f03c60133f293b122b8b43be4.tar.bz2
tangerine-wallet-browser-4780f825b1bfb33f03c60133f293b122b8b43be4.tar.lz
tangerine-wallet-browser-4780f825b1bfb33f03c60133f293b122b8b43be4.tar.xz
tangerine-wallet-browser-4780f825b1bfb33f03c60133f293b122b8b43be4.tar.zst
tangerine-wallet-browser-4780f825b1bfb33f03c60133f293b122b8b43be4.zip
Add ComposableObservableStore for subscription management
Diffstat (limited to 'app/scripts/lib')
-rw-r--r--app/scripts/lib/ComposableObservableStore.js49
1 files changed, 49 insertions, 0 deletions
diff --git a/app/scripts/lib/ComposableObservableStore.js b/app/scripts/lib/ComposableObservableStore.js
new file mode 100644
index 000000000..688594b6d
--- /dev/null
+++ b/app/scripts/lib/ComposableObservableStore.js
@@ -0,0 +1,49 @@
+const ObservableStore = require('obs-store')
+
+/**
+ * An ObservableStore that can composes a flat
+ * structure of child stores based on configuration
+ */
+class ComposableObservableStore extends ObservableStore {
+ /**
+ * Create a new store
+ *
+ * @param {Object} [initState] - The initial store state
+ * @param {Object} [config] - Map of internal state keys to child stores
+ */
+ constructor (initState, config) {
+ super()
+ this.updateStructure(config)
+ }
+
+ /**
+ * Composes a new internal store subscription structure
+ *
+ * @param {Object} [config] - Map of internal state keys to child stores
+ */
+ updateStructure (config) {
+ this.config = config
+ this.removeAllListeners()
+ for (const key in config) {
+ config[key].subscribe((state) => {
+ this.updateState({ [key]: state })
+ })
+ }
+ }
+
+ /**
+ * Merges all child store state into a single object rather than
+ * returning an object keyed by child store class name
+ *
+ * @returns {Object} - Object containing merged child store state
+ */
+ getFlatState () {
+ let flatState = {}
+ for (const key in this.config) {
+ flatState = { ...flatState, ...this.config[key].getState() }
+ }
+ return flatState
+ }
+}
+
+module.exports = ComposableObservableStore