Hi everyone, I have been playing with Elixir for a bit and I was told in passing that performing heavy lifting in a Genserver’s init
call is an anti-pattern. If so, what are some patterns to do it the right way ?
For example, in the code below, I attempt at sending a message to the process itself and performing the task async. However, it seems like due to some sort of race condition(?), the last line of the handle_info
where the process prints out the character count never works.
I am curious about what might be happening here?
defmodule Nine.PartOne do
use GenServer
require Logger
# API
def start_link(state) do
GenServer.start_link(__MODULE__, state, name: __MODULE__)
end
@impl true
def init(state) do
Logger.info("I got started")
file_path = Application.get_env(:adventofcode, :filepath)
Process.send(self(), {:solve, file_path}, [])
{:ok, state}
end
@impl true
def handle_info({:solve, file_path}, _state) do
IO.puts("I got the message") #this is printed
res =
File.read!(file_path)
|> String.graphemes()
|> Enum.reduce(
0,
fn _x, acc ->
acc+1
end
)
#this is never printed
Logger.debug("The result is #{inspect(res)}")
end
end