Repository navigation
Expand file tree
/
Copy pathmodel-observer.js
More file actions
82 lines (74 loc) · 2.23 KB
/
Copy pathmodel-observer.js
File metadata and controls
82 lines (74 loc) · 2.23 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
export default class ModelObserver {
constructor({fetchData, didUpdate}) {
this.fetchData = fetchData || (() => {});
this.didUpdate = didUpdate || (() => {});
this.activeModel = null;
this.activeModelData = null;
this.activeModelUpdateSubscription = null;
this.inProgress = false;
this.pending = false;
}
setActiveModel(model) {
if (model !== this.activeModel) {
if (this.activeModelUpdateSubscription) {
this.activeModelUpdateSubscription.dispose();
this.activeModelUpdateSubscription = null;
}
this.activeModel = model;
this.activeModelData = null;
this.inProgress = false;
this.pending = false;
this.didUpdate(model);
if (model) {
this.activeModelUpdateSubscription = model.onDidUpdate(() => this.refreshModelData(model));
return this.refreshModelData(model);
}
}
return null;
}
refreshModelData(model = this.activeModel) {
if (this.inProgress) {
this.pending = true;
return null;
}
this.lastModelDataRefreshPromise = this._refreshModelData(model);
return this.lastModelDataRefreshPromise;
}
async _refreshModelData(model) {
try {
this.inProgress = true;
const fetchDataPromise = this.fetchData(model);
this.lastFetchDataPromise = fetchDataPromise;
const modelData = await fetchDataPromise;
// Since we re-fetch immediately when the model changes,
// we need to ensure a fetch for an old active model
// does not trample the newer fetch for the newer active model.
if (fetchDataPromise === this.lastFetchDataPromise) {
this.activeModel = model;
this.activeModelData = modelData;
this.didUpdate(model);
}
} finally {
this.inProgress = false;
if (this.pending) {
this.pending = false;
this.refreshModelData();
}
}
}
getActiveModel() {
return this.activeModel;
}
getActiveModelData() {
return this.activeModelData;
}
getLastModelDataRefreshPromise() {
return this.lastModelDataRefreshPromise;
}
hasPendingUpdate() {
return this.pending;
}
destroy() {
if (this.activeModelUpdateSubscription) { this.activeModelUpdateSubscription.dispose(); }
}
}