Next lesson playing in 5 seconds

  • Overview
  • Transcript

3.5 Tasks and Agents

In this lesson, I'll teach you about tasks and agents, which you can use when you don't need the complexity of a GenServer.

3.5 Tasks and Agents

Hi, and welcome back to Get Started With Elixir. In this lesson, we are going to talk about tasks and agents. They're commonly used when having a GenServer would be overkill. The task is often used to calculate a value asynchronously. It can be called either by providing an anonymous function or by providing a module name, a function name as an item and a list of arguments. To wait for the results of a task, you can use the Task.await function, parsing the task's pid. Let's look at our Fibonacci example from the processes lesson. First, we parse the Fibonacci module and fib item to the async method. Then we used again, to wait for the results. You can also supervise tasks with the start_child function, like we did with the wallets in our OTP application. Tasks will only be restarted if they crash, which makes them great for background processing. You should also know that tasks are linked by default, so when a task crashes the process that spawns it will as well, when the task is not in a supervision tree. The second concept is Agent, an agent is a simple abstraction around state. This means it is useful when you want to store a value, but eliminate the need for a GenServer. I'm going to show you now how you can replace the simple wallet example we did in the lesson about then Genserver, with an agent. First, I'm going to rename the start function to start_link. It is always a good idea to use the one you are going to use internally in this case, as the naming communicates if a process will be linked or not. Within the function, we can call Agent.start_link and parse the function that returns the amount. Then we can change our public API to use Agents as well. Instead of Genserver.cost, I'm going to call Agent.update. And parse in the wallet and then anonymous function that uses the amount to calculate the new state. The same will be done for the take_out function. And to fetch the amount, I'm using Agent.get to retrieve the value. We can now get rid of all the GenServer API. To recap, Tasks and Agents are often used when GenServer is overkill. You can use a task to calculate values asynchronously and wait for the result of tasks that await. Tasks are linked by default but can be supervised. Agents are used to store state. In the next lesson we are going to look at nodes and how we can distribute processes with them. See you there.

Back to the top