Search code examples
erlangerlang-otpgen-server

Why Erlang/OTP gen_server callback module must provide handle_cast function?


I can understand why a callback module must provide init and handle_call functions. init is for creating the initial state, and handle_call is the main purpose for creating a server process: to serve requests.

But I don't understand why handle_cast is required. Couldn't gen_server module provide a default implementation, like it does for many other callbacks? It could be a noop like

handle_cast(_, State) -> {noreply, State}.

It seems to me that the majority of callback modules provide noops like this one anyway.


Solution

  • handle_cast is similar to handle_call, and is used for asynchronous calls to the gen_server you're running (calls are synchronous). It is handling requests for you, just not with a reply as a call does.

    Similarly to gen_call it can alter the state of your gen_server (or leave it as is, up to your needs and implementation). Also it can stop your server, hibernate, etc. just like your calls - see learn you some erlang for examples and a broader explanation.

    It "can be a noop" as you said in the question, but in some cases it's better to implement and handle async calls to your server.