You pass the using
operator two parameters:
- a factory function that creates a disposable resource
- a factory function that creates an Observable
When an observer subscribes to the Observable returned from using
, using
will
use the Observable factory function to create the Observable the observer will observe, while at the same
time using the resource factory function to create whichever resource you have designed it to make. To
dispose of the resource, call the dispose
method of the subscription that was returned from
the subscribe
call you used to subscribe an observer to the Observable that you modified
with using
.
Sample Code
/* Using an AsyncSubject as a resource which supports the .dispose method */
function DisposableResource(value) {
this.value = value;
this.disposed = false;
}
DisposableResource.prototype.getValue = function () {
if (this.disposed) {
throw new Error('Object is disposed');
}
return this.value;
};
DisposableResource.prototype.dispose = function () {
if (!this.disposed) {
this.disposed = true;
this.value = null;
}
console.log('Disposed');
};
var source = Rx.Observable.using(
function () { return new DisposableResource(42); },
function (resource) {
var subject = new Rx.AsyncSubject();
subject.onNext(resource.getValue());
subject.onCompleted();
return subject;
}
);
var subscription = source.subscribe(
function (x) { console.log('Next: ' + x); },
function (err) { console.log('Error: ' + err); },
function () { console.log('Completed'); });
using
is found in each of the following distributions: