Mark Elston (105) [Avatar] Offline
I seem to have completely misunderstood the GenServer example in chapter 4. When the idea of GenServer was presented it sounded like a general purpose (or generic) communications channel between client and server applications. I expected to see the client making theGenServer call and cast functions. However, it is the server code (Metex.Worker) that is making these calls. This makes it appear that GenServer is placed between the server and the server, if that makes sense.

I am not sure what to make of this example or what GenServer is doing for us in this case.
alamba78 (10) [Avatar] Offline
GenServer is a way to facilitate the communication between a client and server in a predictable and fault-tolerant way that allows you to keep and manage state. The Metex.Worker module (worker.ex) is being used by the client and the server. The client in the example is the iex shell and the server is the GenServer that is invoked by the shell with the command,
 {:ok, pid} = Metex.Worker.start_link
. This creates the separate server process from the shell/client process.

When you said that the call and cast are being done in the server, that is actually not true. The client (iex shell) has invoked the call as it is wrapped in get_temperature(pid, location). get_temperature wraps a call to . And makes a synchronous call to the server's handle_call/3.

If you get the source code from github or look at table 4.3, you will understand it better.

GenServer.start_link,, and Genserver.cast are Client APIs and init, handle_call, and handle_cast are Server APIs.

It's a little weird to wrap your head around at first, but try to sketch out the processes on paper and place all the relevant function calls with the appropriate process and it makes a lot of sense visually.

Hope that helps a bit.