@grafana/faro-core
Version:
Core package of Faro.
79 lines • 2.85 kB
JavaScript
export class Observable {
constructor() {
this.subscribers = [];
}
subscribe(subscriber) {
this.subscribers.push(subscriber);
return {
unsubscribe: () => this.unsubscribe(subscriber),
};
}
unsubscribe(subscriber) {
this.subscribers = this.subscribers.filter((sub) => sub !== subscriber);
}
notify(value) {
this.subscribers.forEach((subscriber) => subscriber(value));
}
first() {
const result = new Observable();
const internalSubscriber = (data) => {
result.notify(data);
subscription.unsubscribe();
};
const subscription = this.subscribe(internalSubscriber);
const resultUnsubscribeFn = result.unsubscribe.bind(result);
return this.withUnsubscribeOverride(result, resultUnsubscribeFn, internalSubscriber);
}
takeWhile(predicate) {
const result = new Observable();
const internalSubscriber = (value) => {
if (predicate(value)) {
result.notify(value);
}
else {
result.unsubscribe(internalSubscriber);
}
};
this.subscribe(internalSubscriber);
const resultUnsubscribeFn = result.unsubscribe.bind(result);
return this.withUnsubscribeOverride(result, resultUnsubscribeFn, internalSubscriber);
}
filter(predicate) {
const result = new Observable();
const internalSubscriber = (value) => {
if (predicate(value)) {
result.notify(value);
}
};
this.subscribe(internalSubscriber);
const resultUnsubscribeFn = result.unsubscribe.bind(result);
return this.withUnsubscribeOverride(result, resultUnsubscribeFn, internalSubscriber);
}
merge(...observables) {
const mergerObservable = new Observable();
const subscriptions = [];
observables.forEach((observable) => {
const subscription = observable.subscribe((value) => {
mergerObservable.notify(value);
});
subscriptions.push(subscription);
});
const originalUnsubscribeAll = mergerObservable.unsubscribeAll.bind(mergerObservable);
mergerObservable.unsubscribe = () => {
subscriptions.forEach((subscription) => subscription.unsubscribe());
originalUnsubscribeAll();
};
return mergerObservable;
}
withUnsubscribeOverride(observable, resultUnsubscribeFn, internalSubscriber) {
observable.unsubscribe = (subscriber) => {
resultUnsubscribeFn(subscriber);
this.unsubscribe(internalSubscriber);
};
return observable;
}
unsubscribeAll() {
this.subscribers = [];
}
}
//# sourceMappingURL=reactive.js.map