What are GenServers in Elixir?
Overview
OTP is a library in Elixir and has a GenServer module that uses the common interface to handle concurrency.
What is Elixir?
Elixir is a dynamic, functional programming language. It is successful in making applications across a wide range of industries.
What are 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:
GenServercan be synchronous when the caller needs immediate response. It can be invoked byGenServer.call/3. -
Asynchronous:
GenServercan be asynchronous when the caller does not need any immediate response. It can be invoked byGenServer.cast/2.
Components of a GenServer
- API(s): Clients or servers API are represented by making new functions with the required calls. It happens when
GenServerfunctions 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 theuse GenServerfunctions due to its overridable ability to alter the behavior.
def start(_type, _args) dochildren = [{ Mastery.Boundary.QuizManager,[name: Mastery.Boundary.QuizManager] }]
- Registry: The name registration process in
GenServerstarts 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:globalmodule.
{:via, module, name}: This is used to register the server through an alternative registry.
GenServer Callbacks
GenServer.start_link: This startsGenServerand 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 byGenServer.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 byGenServer.cast/2.handle_info: This is used to handle all other messages.handle_continue: This continues the instructions.
Note: After we add command
use GenServerto the module, it will let Elixir add all the callbacks, unless they need to be customised.
Why is 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