53 lines
1.4 KiB
TypeScript
53 lines
1.4 KiB
TypeScript
import { Injectable } from '@angular/core';
|
|
import { WebSocketService } from './websocket.service';
|
|
import { Subject, BehaviorSubject, merge } from 'rxjs';
|
|
import { take } from 'rxjs/operators';
|
|
|
|
@Injectable()
|
|
export abstract class ConfigServiceBase {
|
|
initDone = false;
|
|
keys = new Array<string>();
|
|
mandatoryConfigs = new Array<any>();
|
|
configDone = new Subject<void>();
|
|
|
|
constructor(private webSocketService: WebSocketService) {}
|
|
|
|
init() {
|
|
if (!this.initDone) {
|
|
this.waitForMandatoryConfigs();
|
|
this.subscribeConfigKeys();
|
|
this.initDone = true;
|
|
}
|
|
}
|
|
|
|
waitForMandatoryConfigs() {
|
|
const firstConfigs = new Array<any>();
|
|
this.mandatoryConfigs.forEach((config) => {
|
|
const requiredEmitCount = config instanceof BehaviorSubject ? 2 : 1;
|
|
firstConfigs.push(config.pipe(take(requiredEmitCount)));
|
|
});
|
|
|
|
merge(...firstConfigs).subscribe({complete: () => {
|
|
this.configDone.next();
|
|
this.configDone.complete();
|
|
}});
|
|
}
|
|
|
|
subscribeConfigKeys() {
|
|
this.webSocketService.connect();
|
|
this.keys.forEach(key =>
|
|
this.webSocketService.observeKey<any>(key).subscribe(this.handleConfig.bind(this))
|
|
);
|
|
}
|
|
|
|
handleConfig(message: any) {
|
|
Object.keys(message).filter(key => key !== 'key').forEach(key => {
|
|
if (this[key] === undefined) {
|
|
console.log(`Invalid ${this.keys} config key "${key}"!`);
|
|
} else {
|
|
this[key].next(message[key]);
|
|
}
|
|
});
|
|
}
|
|
}
|