What is Task in Elixir?
Answer
Task is an OTP abstraction for one-shot asynchronous computations. Unlike GenServer (long-lived stateful processes), Tasks are for running a single computation and getting the result. async/await: task = Task.async(fn -> slow_computation() end); result = Task.await(task, 5000) — starts computation in a new process, blocks until result with timeout. start/async_stream: fire-and-forget computation. Task.async_stream: process a list concurrently with bounded parallelism: results = 1..100 |> Task.async_stream(&fetch_item/1, max_concurrency: 10) |> Enum.to_list(). Task.Supervisor: supervise dynamically started tasks — handle failures and restart policies. Tasks are supervised by the calling process by default (linked). Use Task.Supervisor.async_nolink for independent tasks. Tasks are perfect for parallel API calls, background computations, and data pipeline stages where you want structured concurrency without a full GenServer.
More Elixir Questions
View all →- Intermediate How do Elixir supervisors implement fault tolerance?
- Intermediate What is Phoenix Channels and how do WebSockets work in Elixir?
- Intermediate What is Elixir's concurrency model compared to threads?
- Intermediate What are Elixir behaviours?
- Intermediate What is Elixir's error handling approach?