This repository has been archived by the owner on Apr 20, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
refcountdisposable.js
64 lines (56 loc) · 1.7 KB
/
refcountdisposable.js
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
'use strict';
var Disposable = require('./disposable');
function InnerDisposable(disposable) {
this._disposable = disposable;
}
InnerDisposable.prototype.dispose = function () {
var temp = this._disposable;
this._disposable = null;
temp && temp._release();
};
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
function RefCountDisposable(disposable) {
this._disposable = disposable;
this.isDisposed = false;
this._isPrimaryDisposed = false;
this._count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed && !this._isPrimaryDisposed) {
this._isPrimaryDisposed = true;
if (this._count === 0) {
this.isDisposed = true;
this._disposable.dispose();
this._disposable = null;
this.isDisposed = true;
}
}
};
RefCountDisposable.prototype._release = function () {
if (this._disposable) {
this._count--;
if (this._isPrimaryDisposed && this._count === 0) {
this._disposable.dispose();
this._disposable = null;
this.isDisposed = true;
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
if (this.isDisposed) {
return Disposable.empty;
} else {
this._count++;
return new InnerDisposable(this);
}
};
module.exports = RefCountDisposable;