UNPKG

2.72 kBPlain TextView Raw
1// *****************************************************************************
2// Copyright (C) 2018 TypeFox and others.
3//
4// This program and the accompanying materials are made available under the
5// terms of the Eclipse Public License v. 2.0 which is available at
6// http://www.eclipse.org/legal/epl-2.0.
7//
8// This Source Code may also be made available under the following Secondary
9// Licenses when the conditions for such availability set forth in the Eclipse
10// Public License v. 2.0 are satisfied: GNU General Public License, version 2
11// with the GNU Classpath Exception which is available at
12// https://www.gnu.org/software/classpath/license.html.
13//
14// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
15// *****************************************************************************
16
17import { injectable, inject } from 'inversify';
18import { Emitter, Event } from '../common/event';
19import { Deferred } from '../common/promise-util';
20import { ILogger } from '../common/logger';
21import { FrontendApplicationState } from '../common/frontend-application-state';
22
23export { FrontendApplicationState };
24
25@injectable()
26export 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}