aboutsummaryrefslogtreecommitdiffstats
path: root/app/scripts/lib/observable/host.js
diff options
context:
space:
mode:
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