Search code examples
elixirnerves-project

Task like GPIO read forever should be a recursive function or GenServer?


I am monitoring a value continuously for detection. I am wondering will it work reliably if it is a recursive function? Or I should create a Genserver and call it continuously so that it can handle failures? Which are the best cases for using Genservers and which are not.


Solution

  • A GenServer is also just a recursively called function, but it's running in its own process and has some additional functionality on top.

    You'll want to model long-running processes as GenServer for several reasons:

    • Parallelism - if implemented as a GenServer, aka a separate Process, the system will be able to do other things in parallel
    • Isolate errors - if the GPIO code crashes you don't want to affect the rest of the system
    • Supervision - having a GenServer allows the system to re-start on failures. It also gives you the ability to define other processes that depend on the GPIO process, e.g. consumers of the data.

    I recommend reading the chapter "Working with Multiple Processes" from "Programming Elixir" by Dave Thomas to learn more about processes etc.