Cześć,

piszę sobie handlera do obsługi RSocket i nie wiem jak uniknąć wielu równoległych połączeń WebSocket z backendem. Kod w uproszczeniu wygląda tak:

Kopiuj
class RSocketHandler {
  constructor({
    url = "http://localhost:8080/rsocket",
    debug = false,
    store = null
  } = {}) {
    this.url = url;
    this.debug = debug;
    this.store = store;    
    this.socket = null;
  }

  isConnected() {
    if (this.socket) return this.socket.availability();
    return 0;
  }

  connect(completeCallback) {   

    const client = new RSocketClient({
      // send/receive JSON objects instead of strings/buffers
	  //....      
    });
    client.connect().subscribe({
      onComplete: socket => {
        if (this.isConnected()) {
          socket.close();
        } else {
          this.socket = socket;
        }        
        if (completeCallback) completeCallback(socket);
      },
      onError: error => {
        console.error(error);
      },
      onSubscribe: cancel => {
        console.log(cancel);
      }
    });
  }

  requestResponse(payload, completeCallback, errorCallback, subscribeCallback) {    
    if (!this.isConnected()) {
      console.log("not connected...");
      this.connect(socket => {
        return this.requestResponse(
          payload,
          completeCallback,
          errorCallback,
          subscribeCallback
        );
      });
    } else {
      this.socket
        .requestResponse({
          data: payload.data,
          metadata: String.fromCharCode(payload.route.length) + payload.route
        })
        .subscribe({
          onComplete: data => {
            console.log(data.data);
            if (completeCallback) completeCallback(data);
          },
          onError: error => {
            console.error(error);
            if (errorCallback) errorCallback(error);
          },
          onSubscribe: cancel => {
            if (errorCallback) subscribeCallback(cancel);
          }
        });
    }
  }
}

Z komponentów na stronie wywołuję requestResponse i jeśli nie ma nawiązanego połączenia, to się łączę i ponawiam request.

Problem jest wtedy, gdy nie ma połączenia, a na jednej stronie znajduje się wiele komponentów. Wtedy każdy z nich poprzez wywołanie requestResponse nawiązuje oddzielne połączenie. Jak tego uniknąć?