timing-provider
Version:
An implementation of the timing provider specification.
51 lines • 2.04 kB
JavaScript
import { Observable, Subject, skip, take } from 'rxjs';
import { ultimately } from './ultimately';
export const demultiplexMessages = (getClientId, timer) => (source) => new Observable((observer) => {
const subjects = new Map();
const completeAll = () => {
subjects.forEach(([subject, subscription]) => {
if (subject === null) {
subscription.unsubscribe();
}
else {
subject.complete();
}
});
};
const isActive = (remoteClientId) => getClientId() < remoteClientId;
return source.pipe(ultimately(() => completeAll())).subscribe({
complete() {
observer.complete();
},
error(err) {
observer.error(err);
},
next(event) {
var _a;
const remoteClientId = event.client.id;
const [subject, subscription] = (_a = subjects.get(remoteClientId)) !== null && _a !== void 0 ? _a : [null, null];
if (event.type === 'termination') {
if (subscription !== null) {
subscription.unsubscribe();
}
if (subject !== null) {
subject.complete();
}
subjects.set(remoteClientId, [
null,
timer.pipe(skip(isActive(remoteClientId) ? 1 : 0), take(1)).subscribe(() => subjects.delete(remoteClientId)) // tslint:disable-line:rxjs-no-nested-subscribe
]);
}
else if (subject === null && subscription === null) {
const newSubject = new Subject();
subjects.set(remoteClientId, [newSubject, null]);
observer.next([remoteClientId, isActive(remoteClientId), newSubject.asObservable()]);
newSubject.next(event);
}
else if (subscription === null) {
subject.next(event);
}
}
});
});
//# sourceMappingURL=demultiplex-messages.js.map