diff options
author | Steve Klebanoff <steve.klebanoff@gmail.com> | 2018-11-09 06:57:39 +0800 |
---|---|---|
committer | Steve Klebanoff <steve.klebanoff@gmail.com> | 2018-11-09 06:57:39 +0800 |
commit | 7acaae37a969339d1b4971f80d7fd842266bb60b (patch) | |
tree | 08925eec8cc75c525d4a384383383cc07d75f77c /packages/instant/src/util | |
parent | c84e163edb329b478749cad09f222cc12e3698fe (diff) | |
download | dexon-sol-tools-7acaae37a969339d1b4971f80d7fd842266bb60b.tar.gz dexon-sol-tools-7acaae37a969339d1b4971f80d7fd842266bb60b.tar.zst dexon-sol-tools-7acaae37a969339d1b4971f80d7fd842266bb60b.zip |
feat(instant): Heartbeat for updating account info
Diffstat (limited to 'packages/instant/src/util')
-rw-r--r-- | packages/instant/src/util/hearbeats.ts | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/packages/instant/src/util/hearbeats.ts b/packages/instant/src/util/hearbeats.ts new file mode 100644 index 000000000..19b448bef --- /dev/null +++ b/packages/instant/src/util/hearbeats.ts @@ -0,0 +1,47 @@ +import * as _ from 'lodash'; + +import { asyncData } from './../redux/async_data'; +import { Store } from './../redux/store'; + +export class AccountUpdateHeartbeat { + private _intervalId?: number; + private _pendingRequest?: boolean; + private _store?: Store; + + public start(store: Store, intervalTimeMs: number): void { + if (!_.isUndefined(this._intervalId)) { + throw new Error('Heartbeat is running, please stop before restarting'); + } + this._store = store; + // Kick off initial first request + this._performActionAsync(true); + // Set interval for heartbeat + this._intervalId = window.setInterval(this._performActionAsync.bind(this, false), intervalTimeMs); + } + + public stop(): void { + if (!_.isUndefined(this._intervalId)) { + window.clearInterval(this._intervalId); + this._resetState(); + } + } + + private _resetState(): void { + this._intervalId = undefined; + this._pendingRequest = false; + this._store = undefined; + } + + private async _performActionAsync(setLoading: boolean): Promise<void> { + if (this._pendingRequest || _.isUndefined(this._store)) { + return; + } + + this._pendingRequest = true; + try { + await asyncData.fetchAccountInfoAndDispatchToStore(this._store, { setLoading }); + } finally { + this._pendingRequest = false; + } + } +} |