From 6cf3217f7f5da5b8ecfbb52e7c761ab91b1c4c97 Mon Sep 17 00:00:00 2001 From: Stefan Malzner Date: Sat, 13 Apr 2019 20:58:00 +0200 Subject: Use store reactions --- src/features/settingsWS/store.js | 33 ++++++++++++++++++++++++--------- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/src/features/settingsWS/store.js b/src/features/settingsWS/store.js index 8e1d455f1..0f1feebb9 100755 --- a/src/features/settingsWS/store.js +++ b/src/features/settingsWS/store.js @@ -1,4 +1,4 @@ -import { observable, reaction } from 'mobx'; +import { observable } from 'mobx'; import WebSocket from 'ws'; import ms from 'ms'; @@ -19,13 +19,12 @@ export class SettingsWSStore extends Store { constructor(stores, api, actions, state) { super(stores, api, actions); this.state = state; - } - setup() { - reaction(() => this.stores.user.data.id, this.connect.bind(this), { - fireImmediately: true, - }); - reaction(() => !this.connected, this.reconnect.bind(this)); + this.registerReactions([ + this._initialize.bind(this), + this._reconnect.bind(this), + this._close.bind(this), + ]); } connect() { @@ -72,7 +71,7 @@ export class SettingsWSStore extends Store { clearTimeout(this.pingTimeout); this.pingTimeout = setTimeout(() => { - debug('Terminating connection reconnecting in 35'); + debug('Terminating connection, reconnecting in 35'); this.ws.terminate(); this.connected = false; @@ -88,7 +87,15 @@ export class SettingsWSStore extends Store { } } - reconnect() { + // Reactions + + _initialize() { + if (this.stores.user.data.id) { + this.connect(); + } + } + + _reconnect() { if (!this.connected) { debug('Trying to reconnect in 30s'); this.reconnectTimeout = setInterval(() => { @@ -100,6 +107,14 @@ export class SettingsWSStore extends Store { clearInterval(this.reconnectTimeout); } } + + _close() { + if (!this.stores.user.isLoggedIn && this.ws) { + debug('Terminating connection'); + this.ws.terminate(); + this.ws = null; + } + } } export default SettingsWSStore; -- cgit v1.2.3-70-g09d2