Programming Elixir Chapter 21 Notes


Tasks and Agents

Agents are processes that maintain state. Effectively, this is wrapping the Stack.Stash process we’ve implemented earlier.

  1. An Elixir Task wraps OTP message passing.

  2. Instead of calling a process with start_link and then waiting for the response with receive, you start the process with Task.async and then Task.await on the specific pid.

  3. Tasks are OTP servers and can be added to the Supervisor tree.

  4. Task.await cannot be used with tasks started by the Supervisor as we don’t know the pid to await.

  5. The first Agent example shows passing an initialization function vs. a value. Need to research if this is mandatory.

  6. The phrase &(&1) is the identify function and used to retrieve the current state.

    {:ok, count } = Agent.start(fn -> 0 end)
    Agent.get(count, &(&1))
    Agent.update(count, &(&1 + 1))

All notes and comments are my own opinion. Follow me at @rgacote@genserver.social