Genserver inner calls

Hello,

Within a genserver, if a function needs to call another server function, would you write:

  def handle_cast({:fetch, name}, state) when is_string(name) do
    GenServer.cast(name, {:fetch, Model.new(name)})
    {:noreply, state}
  end

  def handle_cast({:fetch, model}, state) do
    intern_method(model)
    {:noreply, state}
  end

OR

  def handle_cast({:fetch, name}, state) when is_string(name) do
    intern_method(Model.new(name))
  end
  def handle_cast({:fetch, d}, state) do
    intern_method(d)
  end

We have a disagreement with a coworker. :smile:

1 Like

The latter, because the first one adds messaging to the equation and in case of calls can even result in deadlocks.

8 Likes

A GenServer should only send itself a message if it is a call that should be performed later (like trying something again in a minute). When you want something to happen right now, directly call the function as normal.

5 Likes

Thanks guys, you confirmed what I thought. :smile: