How to retry / reconnect to Websocket server with RxJS WebSocketSubject

Viewed 912

I found various solutions for RxJS WebSocketSubject automatic reconnection, but nothing worked for me.

In my RxJS 6.5 / Angular Code there is a connectToWebsocket() function which is executed once on startup, containing this:

    const openObserver: NextObserver<Event> = {
        next: () => console.debug('[Websocket] Connected')
    };
    const closeObserver: NextObserver<CloseEvent> = {
        next: () => console.debug('[Websocket] Disconnected')
    };

    // Connect to WebSocket Server
    this.websocketConnection= new WebSocketSubject({
        url: "ws://localhost:4000",
        deserializer: e => e.data,
        openObserver,
        closeObserver
    });

After creating the Subject, I subscribe to it:

    this.websocketConnection.subscribe((msg) => {
        this.data = msg;
    },
    (err) => {
        console.log("Error on on connection", err);
    },
    () => {
        console.log("Connection closed");
    });

So now, if initially or while connected, the connection is closed by any circumstances. How can I reconnect to the websocket server? Do I need to write an own reconnection strategy or is there one already in RxJS?

Thanks in advance!

0 Answers
Related