aboutsummaryrefslogtreecommitdiffstats
path: root/packages/instant/src/util/hearbeats.ts
blob: 443fd13ec09f814a9244dcde95105aa245e5f03b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// TODO: rename file

import * as _ from 'lodash';

import { asyncData } from './../redux/async_data';
import { Store } from './../redux/store';

type HeartbeatableFunction = () => Promise<void>;
export class Heartbeater {
    private _intervalId?: number;
    private _pendingRequest: boolean;
    private _performingFunctionAsync: HeartbeatableFunction;

    public constructor(_performingFunctionAsync: HeartbeatableFunction) {
        this._performingFunctionAsync = _performingFunctionAsync;
        this._pendingRequest = false;
    }

    public start(intervalTimeMs: number): void {
        if (!_.isUndefined(this._intervalId)) {
            throw new Error('Heartbeat is running, please stop before restarting');
        }
        this._trackAndPerformAsync();
        this._intervalId = window.setInterval(this._trackAndPerformAsync.bind(this), intervalTimeMs);
    }

    public stop(): void {
        if (this._intervalId) {
            window.clearInterval(this._intervalId);
        }
        this._intervalId = undefined;
        this._pendingRequest = false;
    }

    private async _trackAndPerformAsync(): Promise<void> {
        if (this._pendingRequest) {
            return;
        }

        this._pendingRequest = true;
        try {
            this._performingFunctionAsync();
        } finally {
            this._pendingRequest = false;
        }
    }
}

export const generateAccountHeartbeater = (store: Store): Heartbeater => {
    return new Heartbeater(async () => {
        await asyncData.fetchAccountInfoAndDispatchToStore(store, { setLoading: false });
    });
};