Rejoining Channels with updated params

During network disconnection or reconnection of a socket, there might be a need to update the params passed during reconnection. For sockets, this can be achieved by updating it’s params attribute.

let socket = new Socket("/socket", {params: {token: "123"}});
socket.connect();
socket.onError(function(error) { 
  // reconnect failed due to token expiry
  token = getNewToken();
  socket.params = () => ({ token: token }) // Updates params for socket
});

Once the params are updated, it automatically tries to reconnect with new params.

Consider the same scenario for a channel join. Say you had to pass a token in params while joining a channel for authorization.

  let room_id = 123;
  let text_channel = socket.channel(`room:${room_id}`, {room_token: xxx});

  text_channel.join()
    .receive("ok", (messages) => {
      console.log(`Room ${room_id} joined!`);
    })
    .receive("error", (response) => {
      console.log("Failed to join room", response)
    })
    .receive("timeout", () => {
      console.log("Networking issue. Still waiting...")
    });

Now due to a network disconnection, the socket (and associated channels) disconnect. On reconnecting, the socket reconnects and the channels automatically rejoin. But in this case, the existing room_token for the same channel has expired. How can the params for this channel be updated?

channels params also accepts an object literal or a function. So you can either set myChannel.params = {new: ...} in channel error or use a closure like you are in the socket example.

2 Likes