OTP is a library in Elixir and has a GenServer
module that uses the common interface to handle concurrency.
Elixir is a dynamic, functional programming language. It is successful in making applications across a wide range of industries.
GenServers
?GenServers
are one of the processes that OTP uses. Primarily, GenServers
are used to module the behavior. It can be synchronous and asynchronous. It provides interface functions that can eventually be used for tracing and error reporting.
Synchronous: GenServer
can be synchronous when the caller needs immediate response. It can be invoked by GenServer.call/3
.
Asynchronous: GenServer
can be asynchronous when the caller does not need any immediate response. It can be invoked by GenServer.cast/2
.
GenServer
functions are not used directly.def select_question(name) doGenServer.call(via(name), :select_question)end
child_spec
: This is created after the command. It can be used to supervise the use GenServer
functions due to its overridable ability to alter the behavior.def start(_type, _args) dochildren = [{ Mastery.Boundary.QuizManager,[name: Mastery.Boundary.QuizManager] }]
GenServer
starts with :name
. We use tuples for this, {:global, term}
or {:via, module, name}
.
{:global, term}
: This is used to register the server globally by providing the terms of process and associated PIDs through:global
module.
{:via, module, name}
: This is used to register the server through an alternative registry.
GenServer
CallbacksGenServer.start_link
: This starts GenServer
and connects it to the linked process.def start_link(options \\ [ ]) doGenServer.start_link(__MODULE__, %{ }, options)end
GenServer.call
: This creates a synchronous call to the server.GenServer.cast
: This creates an asynchronous request to the server.handle_call
: This is used to handle synchronous messages that can be invoked by GenServer.call/3
.def handle_call({:lookup_quiz_by_title, quiz_title}, _from, quizzes) do{:reply, quizzes[quiz_title], quizzes}end#handle_call invoking synchronous call to the server with the given arguments
handle_cast
: This is used to handle asynchronous messages that can be invoked by GenServer.cast/2
.handle_info
: This is used to handle all other messages.handle_continue
: This continues the instructions.Note: After we add command
use GenServer
to the module, it will let Elixir add all the callbacks, unless they need to be customised.
GenServer
recommended?GenServer
is a supervised process, which offers synchronous and asynchronous calls. It is flexible in its behavior and it can be changed by calls or casts. In addition to this, it runs the process sequentially instead of running the whole function once.
Free Resources