AG1
AG1

Reputation: 6774

Elixir: Is there a more concise way to run Tasks?

I've just started experimenting with Tasks in Elixir.
1) Is there a more concise way to start N Tasks?
2) would I be better off creating a Map of {symbol, task} vs. a List of Tasks?

stocks=["bsx","wmt"]

# assume this is a long-running function
longfunc = fn(sym) -> "nyse:"<>sym end 

tasks = Enum.reduce(stocks, [], fn(x,acc) -> [Task.async(fn -> longfunc.(x) end)| acc] end )

Enum.map(tasks, &Task.await/1)

Upvotes: 0

Views: 204

Answers (1)

Brett Beatty
Brett Beatty

Reputation: 5973

Task.async_stream/5 provides a simple interface for running a list of tasks. Here's an example using Task.async_stream/3:

["bsx", "wmt"]
|> Task.async_stream(&("nyse:" <> &1))
|> Enum.to_list() # or any stream enumeration
#⇒ [ok: "nyse:bsx", ok: "nyse:wmt"]

Upvotes: 1

Related Questions