Reputation: 163
Is there a way to obtain the socket being subscribed by WebSocketSubject?
When a certain condition happens I need to close the underlying socket.
I tried to close it by complete() but it didn't close the socket. The unsubscribed doesn't work either.
Could anybody help me? Or point me in the right direction?
Upvotes: 3
Views: 5408
Reputation: 111
You can use unsubscribe method.
closeConnection(): void {
this.socket.unsubscribe();
}
Extract for unsubscribe method implemntation :
unsubscribe() {
const { _socket } = this;
if (_socket && (_socket.readyState === 1 || _socket.readyState === 0)) {
_socket.close();
}
this._resetState();
super.unsubscribe();
}
Upvotes: 0
Reputation: 81
More accurate way is to call complete()
on WebSocketSubject
. But there is one more solution. You can obtain socket using code like this. It`s bad, but works too.
var wrapper: any = subject;
wrapper._socket.close();
Upvotes: 0
Reputation: 96889
You can call unsubscribe()
directly on the WebSocketSubject
instance that unsubscribes all observers:
const subject = Observable.webSocket(...);
...
subject.unsubscribe();
See source code: https://github.com/ReactiveX/rxjs/blob/master/src/observable/dom/WebSocketSubject.ts#L269
Upvotes: -1
Reputation: 11
For having correct socket disconnect you should unsubscribe websocketsubject itself, not it's subscription: https://github.com/ReactiveX/rxjs/blob/master/src/internal/observable/dom/WebSocketSubject.ts#L295
Upvotes: 1
Reputation: 117
He said that the unsubscribe did not work. Indeed I had the same problem. I was doing the unsubscribe and it wasn't closed.
I end up using directly the websocket instead of WebSocketSubject, so I could call the method close (which worked).
this._ws = new WebSocket(this.url);
this.messages = Observable.create((observer) => {
this._ws.addEventListener('message', (message) => (
// Et on ajoute chaque message dans l'Observable
observer.next(message)
), false);
// On s'enregistre au erreurs qui surviendraient
// dans la websocket
this._ws.addEventListener('error', (error) => {
// Si un erreur est survenue, on prévient
// l'Observable
console.log('error ws');
observer.error(error)
}, false);
// On s'enregistre à la fermeture du websocket
this._ws.addEventListener('close', () => {
// On met fin à l'Observable
observer.complete()
console.log('complete');
}, false)
})
...
public close() {
console.log('on closing WS');
this._ws.close()
}
I follow this tuto Introduction à RxJS and this one
If you manage to do a reconnect after the server closes the WS, please post it also.
Thanks
Upvotes: 1