1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | import { injectable, inject } from 'inversify';
|
18 | import { Emitter, Event } from '../common/event';
|
19 | import { Deferred } from '../common/promise-util';
|
20 | import { ILogger } from '../common/logger';
|
21 | import { FrontendApplicationState } from '../common/frontend-application-state';
|
22 |
|
23 | export { FrontendApplicationState };
|
24 |
|
25 | @injectable()
|
26 | export class FrontendApplicationStateService {
|
27 |
|
28 | @inject(ILogger)
|
29 | protected readonly logger: ILogger;
|
30 |
|
31 | private _state: FrontendApplicationState = 'init';
|
32 |
|
33 | protected deferred: { [state: string]: Deferred<void> } = {};
|
34 | protected readonly stateChanged = new Emitter<FrontendApplicationState>();
|
35 |
|
36 | get state(): FrontendApplicationState {
|
37 | return this._state;
|
38 | }
|
39 |
|
40 | set state(state: FrontendApplicationState) {
|
41 | if (state !== this._state) {
|
42 | this.doSetState(state);
|
43 | }
|
44 | }
|
45 |
|
46 | get onStateChanged(): Event<FrontendApplicationState> {
|
47 | return this.stateChanged.event;
|
48 | }
|
49 |
|
50 | protected doSetState(state: FrontendApplicationState): void {
|
51 | if (this.deferred[this._state] === undefined) {
|
52 | this.deferred[this._state] = new Deferred();
|
53 | }
|
54 | const oldState = this._state;
|
55 | this._state = state;
|
56 | if (this.deferred[state] === undefined) {
|
57 | this.deferred[state] = new Deferred();
|
58 | }
|
59 | this.deferred[state].resolve();
|
60 | this.logger.info(`Changed application state from '${oldState}' to '${this._state}'.`);
|
61 | this.stateChanged.fire(state);
|
62 | }
|
63 |
|
64 | reachedState(state: FrontendApplicationState): Promise<void> {
|
65 | if (this.deferred[state] === undefined) {
|
66 | this.deferred[state] = new Deferred();
|
67 | }
|
68 | return this.deferred[state].promise;
|
69 | }
|
70 |
|
71 | reachedAnyState(...states: FrontendApplicationState[]): Promise<void> {
|
72 | return Promise.race(states.map(s => this.reachedState(s)));
|
73 | }
|
74 | }
|