Unsubscribe from port within port subscription callback?

I’m not sure if I’m missing something obvious, but:

I have a subscription to a port.

elmApp.ports.myPort.subscribe(portCallback(elmApp))

On the JavaScript side, inside the callback function to that subscription, I sometimes want to be able to unsubscribe from the port, which will only work if you can pass unsubscribe the same arguments (with reference equality) as you passed to subscribe initially.

function portCallback(elmApp){
  return function(portData){
    /* some code */
    elmApp.ports.myPort.unsubscribe(/* ??? something with reference equality to the current call to portCallback ??? */)
    /* some more code */
  }
}

How does one accomplish this? Is it possible? Am I missing something obvious? The closest possibility I’ve been able to find seems to be argument.callee, but that’s deprecated.

Broader context: I’m running a Phoenix app, and this port subscription sends events down a Phoenix channel. When the channel gets timeout errors, I want to join a new channel and make a new port subscription that sends messages down the new channel, and unsubscribe from the port subscription that would be sending them down the old channel.

I think things fall in place if you name the function with a variable:

function portCallback(elmApp){
  var f = function(portData){
    /* some code */
    elmApp.ports.myPort.unsubscribe(f)
    /* some more code */
  };
  return f;
}
1 Like

OMG, that worked!!! Thanks!!

1 Like

Do you know why this is the case?

@andys8 - OP’s initial reason was correct. I just refactored a bit to achieve the circular reference.

1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.