aboutsummaryrefslogtreecommitdiffstats
path: root/app/scripts/lib/observable/host.js
diff options
context:
space:
mode:
authorkumavis <aaron@kumavis.me>2017-01-12 11:04:19 +0800
committerkumavis <aaron@kumavis.me>2017-01-12 11:31:21 +0800
commit8012ede12698477692b80769781096b559159a32 (patch)
tree17f75325da8f5d0abf2c1f37fa0573320730b6a7 /app/scripts/lib/observable/host.js
parentcc5e9aca4fa2a1e78c49be680405d93ac918bccf (diff)
downloadtangerine-wallet-browser-8012ede12698477692b80769781096b559159a32.tar
tangerine-wallet-browser-8012ede12698477692b80769781096b559159a32.tar.gz
tangerine-wallet-browser-8012ede12698477692b80769781096b559159a32.tar.bz2
tangerine-wallet-browser-8012ede12698477692b80769781096b559159a32.tar.lz
tangerine-wallet-browser-8012ede12698477692b80769781096b559159a32.tar.xz
tangerine-wallet-browser-8012ede12698477692b80769781096b559159a32.tar.zst
tangerine-wallet-browser-8012ede12698477692b80769781096b559159a32.zip
background - introduce ObservableStore
Diffstat (limited to 'app/scripts/lib/observable/host.js')
-rw-r--r--app/scripts/lib/observable/host.js50
1 files changed, 50 insertions, 0 deletions
diff --git a/app/scripts/lib/observable/host.js b/app/scripts/lib/observable/host.js
new file mode 100644
index 000000000..69f674be8
--- /dev/null
+++ b/app/scripts/lib/observable/host.js
@@ -0,0 +1,50 @@
+const Dnode = require('dnode')
+const ObservableStore = require('./index')
+const endOfStream = require('end-of-stream')
+
+//
+// HostStore
+//
+// plays host to many RemoteStores and sends its state over a stream
+//
+
+class HostStore extends ObservableStore {
+
+ constructor (initState, opts) {
+ super(initState)
+ this.opts = opts || {}
+ }
+
+ createStream () {
+ const self = this
+ // setup remotely exposed api
+ let remoteApi = {}
+ if (!self.opts.readOnly) {
+ remoteApi.put = (newState) => self.put(newState)
+ }
+ // listen for connection to remote
+ const dnode = Dnode(remoteApi)
+ dnode.on('remote', (remote) => {
+ // setup update subscription lifecycle
+ const updateHandler = (state) => remote.put(state)
+ self._onConnect(updateHandler)
+ endOfStream(dnode, () => self._onDisconnect(updateHandler))
+ })
+ return dnode
+ }
+
+ _onConnect (updateHandler) {
+ // subscribe to updates
+ this.subscribe(updateHandler)
+ // send state immediately
+ updateHandler(this.get())
+ }
+
+ _onDisconnect (updateHandler) {
+ // unsubscribe to updates
+ this.unsubscribe(updateHandler)
+ }
+
+}
+
+module.exports = HostStore