Implement base class for future config services

This commit is contained in:
Kristóf Tóth 2019-08-28 10:18:35 +02:00
parent 65c7c727f5
commit 41eebc60f6

View File

@ -0,0 +1,53 @@
import { Injectable } from '@angular/core';
import { WebSocketService } from './websocket.service';
import { Subject, BehaviorSubject, forkJoin } 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) {
return;
}
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)));
});
forkJoin(firstConfigs).subscribe(undefined, undefined, () => {
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]);
}
});
}
}