Example of Receiving messages continuously
Closed this issue · 3 comments
I'm setting up a client that talks (Sends and Receive messages) to another Phoenix application. Now I'm able to send messages, but don't know how to receive them as they're are broadcasted from the other App.
It would be nice for this repository to show an example of the implementation of the client let's say within a module so that other users find more ways to use it.
Can you give me a pointer to this?
Thanks a lot!
Here is my implementation.
My way is calling PhoenixChannelClient.join/1
in the GenServer's init/1
callback and receiving messages by the handle_info/2
callback.
However this implementation is too long to be used as an example, so I'll make a proper example.
Thanks.
Thanks @ryo33 going to try it!
I'm going to add the following module as an example of receiving messages continuously.
How about this?
defmodule ChannelClient do
use GenServer
def start_link(channel, opts) do
GenServer.start_link(__MODULE__, [channel: channel, opts: opts], name: __MODULE__)
end
def init([channel: channel, opts: opts]) do
state = %{
handlers: opts[:handlers]
}
case PhoenixChannelClient.join(channel) do
{:ok, _} -> {:ok, state}
{:error, reason} -> {:stop, reason}
:timeout -> {:stop, :timeout}
end
end
def handle_info({event, payload}, state) do
case Map.get(state.handlers, event) do
handler when not is_nil(handler) -> handler.(payload)
_ -> :ok
end
{:noreply, state}
end
end
handers = %{
"event1" => fn payload -> Handler.event1(payload) end,
"event2" => fn payload -> Handler.event2(payload) end
}
ChannelClient.start_link(channel, handlers: handlers)