blob: ecd7c506826513e147e76231370c2042e90c65ae (
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
54
55
56
57
58
59
60
61
62
63
64
65
|
// TODO: rename file
import * as _ from 'lodash';
import { Dispatch } from 'redux';
import { Action } from '../redux/actions';
import { asyncData } from '../redux/async_data';
import { State } from '../redux/reducer';
import { Store } from '../redux/store';
import { updateBuyQuoteOrFlashErrorAsyncForState } from './buy_quote_fetcher';
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 {
await this._performingFunctionAsync();
} finally {
this._pendingRequest = false;
}
}
}
export const generateAccountHeartbeater = (store: Store): Heartbeater => {
return new Heartbeater(async () => {
await asyncData.fetchAccountInfoAndDispatchToStore(store, { setLoading: false });
});
};
export const generateBuyQuoteHeartbeater = (store: Store): Heartbeater => {
return new Heartbeater(async () => {
await updateBuyQuoteOrFlashErrorAsyncForState(store.getState(), store.dispatch);
return Promise.resolve();
});
};
|