forked from aws/aws-toolkit-vscode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpollingSet.ts
More file actions
57 lines (49 loc) · 1.49 KB
/
pollingSet.ts
File metadata and controls
57 lines (49 loc) · 1.49 KB
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
/*!
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
import globals from '../extensionGlobals'
/**
* A useful abstraction that does the following:
* - keep a set of items.
* - if the set is non-empty, run some action every interval seconds.
* - once the set empties, clear the timer
* @param interval the interval in seconds
* @param action the action to perform
*/
export class PollingSet<T> extends Set<T> {
public pollTimer?: NodeJS.Timeout
public constructor(
private readonly interval: number,
private readonly action: () => void
) {
super()
}
public isActive(): boolean {
return this.size !== 0
}
public hasTimer(): boolean {
return this.pollTimer !== undefined
}
public clearTimer(): void {
if (!this.isActive() && this.hasTimer()) {
globals.clock.clearInterval(this.pollTimer)
this.pollTimer = undefined
}
}
private poll() {
this.action()
if (!this.isActive()) {
this.clearTimer()
}
}
// TODO(hkobew): Overwrite the add method instead of adding seperate method. If we add item to set, timer should always start.
public start(id: T): void {
this.add(id)
this.pollTimer = this.pollTimer ?? globals.clock.setInterval(() => this.poll(), this.interval)
}
public override clear(): void {
this.clearTimer()
super.clear()
}
}