Starting dynamically children from a supervisor pattern


I started, as an exercise, a little pet project to fetch tweets via twitter’s stream api using ExTwitter

You can see the supervisor here
My aim would be to integrate it with phoenix channels, however I am using this code, which, seems to me not the most elegant:

  def join("tweets:" <> namespace, payload, socket) do
    unless is_pid(Tweetyodel.Worker.whereis(namespace)) do
      {:ok, _} = Tweetyodel.Worker.Supervisor.start_tweet(namespace)
    if authorized?(payload) do
      {:ok, assign(socket, :namespace, namespace)}
      {:error, %{reason: "unauthorized"}}

Which involves checking if the child is already started (via Tweetyodel.Worker.whereis(namespace))
I am wondering if there’s a different approach to handle this case or if I should just:

even without pattern matching{:ok, _} so that I will ignore the :already_started match, which seems also not a good idea :wink:
Maybe a case statement?

Thanks in advance for the suggestions!

1 Like

I would do a case statement on both the :ok and :already_started responses. That way any error response will get propagated.

1 Like

Thanks @gregvaughn – makes sense!