Azolo / websockex

An Elixir Websocket Client
MIT License
519 stars 100 forks source link

`handle_connect/2` first connection #109

Closed Zat42 closed 2 years ago

Zat42 commented 2 years ago

Is there a way to know in callback handle_connect/2 if this is a first connection or a reconnection?

My problem there is that I initialize something at first connection and I need to do it only once. I couldn't find anything helfpul in Websocket.Conn to help me on this.

Also, I don't understand why there is no init/1 callback like GenSever, is there a specific reason for this?

Azolo commented 2 years ago

I think at one point I had something like an init/1 in there, but I felt that it made the API confusing.

In your case, I would suggest that you have something in your state that signifies that you haven't been through your first connect. If you need to then invoke the other handle_connect/2 with the state updated.

def handle_connect(_, %{connected: true} = state) do
  ...
end

def handle_connect(conn, state) do
  ...
  handle_connect(conn, Map.put(state, :connected, true)) # If you want to run the other `handle_connect/2` instead of return.
end