Tasks

An Elixir task is a function that runs in the background.

 defmodule​ Fib ​do
 def​ of(0), ​do​: 0
 def​ of(1), ​do​: 1
 def​ of(n), ​do​: Fib.of(n-1) + Fib.of(n-2)
 end
 
 IO.puts ​"​​Start the task"
 worker = Task.async(​fn​ -> Fib.of(20) ​end​)
 IO.puts ​"​​Do something else"
 # ...
 IO.puts ​"​​Wait for the task"
 result = Task.await(worker)
 
 IO.puts ​"​​The result is ​​#{​result​}​​"

The call to Task.async creates a separate process that runs the given function. The return value of async is a task descriptor (actually a PID and a ref) that we’ll use to identify the task later.

Once the task is running, the code continues with other work. When it wants to get the function’s value, it calls Task.await ...

Get Programming Elixir 1.3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.