, javascript :
defmodule M do
use GenServer
def start_link(_opts \\ []) do
GenServer.start_link(__MODULE__, nil, name: __MODULE__)
end
def init(_args) do
Process.sleep(1_000)
{:ok, 42}
end
def value() do
start_link()
GenServer.call(__MODULE__, :value)
end
def handle_call(:value, _from, state) do
{:reply, state, state}
end
end
(1..5) |> Enum.each(&IO.inspect(M.value(), label: to_string(&1)))
, @Dogberts: , .
This is an exact analogue of your memoized function using a stage GenServer. GenServer.start_link/3returns one of the following values:
{:ok,
{:error, {:already_started,
However, it does not restart if it is already running. I did not bother to check the return value, since we are all set up anyway: if its the initial start, we call a heavy function, if we were already running, vaklue is already under our fingers state.
source
share