Skip to content

Instantly share code, notes, and snippets.

@AlexDaSoul
Last active July 3, 2018 10:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlexDaSoul/b30a25da547b23e65f1dc530999894de to your computer and use it in GitHub Desktop.
Save AlexDaSoul/b30a25da547b23e65f1dc530999894de to your computer and use it in GitHub Desktop.
ws-10
constructor(@Inject(config) private wsConfig: WebSocketConfig) {
this.wsMessages$ = new Subject<IWsMessage<any>>();
// смотрим конфиг, если пусто, задаем умолчания для реконнекта
this.reconnectInterval = wsConfig.reconnectInterval || 5000;
this.reconnectAttempts = wsConfig.reconnectAttempts || 10;
// при сворачивании коннекта меняем статус connection$ и глушим websocket$
this.config = {
url: wsConfig.url,
closeObserver: {
next: (event: CloseEvent) => {
this.websocket$ = null;
this.connection$.next(false);
}
},
// при коннекте меняем статус connection$
openObserver: {
next: (event: Event) => {
console.log('WebSocket connected!');
this.connection$.next(true);
}
}
};
// connection status
this.status = new Observable<boolean>((observer) => {
this.connection$ = observer;
}).pipe(share(), distinctUntilChanged());
// запускаем реконнект при отсутствии соединения
this.statusSub = this.status
.subscribe((isConnected) => {
this.isConnected = isConnected;
if (!this.reconnection$ && typeof(isConnected) === 'boolean' && !isConnected) {
this.reconnect();
}
});
// говорим, что что-то пошло не так
this.websocketSub = this.wsMessages$.subscribe(
null, (error: ErrorEvent) => console.error('WebSocket error!', error)
);
// коннектимся
this.connect();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment