I've built a GenServer pub/sub to handle async effects from my #phoenix
application, but have been wondering how it handles multiple broadcasts. Given
that a GenServer processes messages from a queue, how can I concurrently handle
those messages.
Answer: by dispatching to Task
defmodule Subscriber do
use GenServer
alias Handler
def start_link(_opts) do
GenServer.start_link(__MODULE__, %{}, name: __MODULE__)
end
@impl true
def init(_) do
Phoenix.PubSub.subscribe(MyPubSub, "my-topic")
{:ok, nil}
end
@impl true
def handle_info(msg, _) do
# Task.start for fire-and-forget
Task.start(Handler, :handle, [msg])
{:noreply, nil}
end
end
defmodule Handler do
def handle({:foo, %{url: url }}) do
# Maybe this is an API request to another service
end
def handle({:bar, %{url: url }}) do
# ...
end
end