3 ms·
Yes. When I open a module I haven't seen before, and the first line that I read is: use GenServer I immediately know how this module behaves in terms of
by fredrikholm 6y ago
Yes.
When I open a module I haven't seen before, and the first line that I read is:
use GenServer
I immediately know how this module behaves in terms of (distributed) concurrency. If I can find where this module is started, I also know how it handles when things go wrong (via supervision trees).
GenServer supports three ways of communicating:
* call -> handle_call (sync)
* cast -> handle_cast (async)
* send -> handle_info (async system messages, signals etc)
Here's an example:
def send_greeting(pid, greeting, from) do
GenServer.call(pid, {:receive_greeting, greeting, from})
end
def handle_call({:receive_greeting, greeting, name}, sender, current_state) do
IO.puts greeting
{:reply, "Hello #{name}!", current_state}
end
------------------------
{:ok, mikes_computer} = Greeter.start_link(:mike)
response = Greeter.send_greeting(mikes_computer, "Hello Mike!", "Joe")
IO.puts response
> "Hello Joe!"
There's more ways to implement concurrency than by GenServers, but it's the combination of GenServers and Supervisors that sets the BEAM and OTP a head above everything else (in this very specific domain of soft realtime distributed servers).