Skip to content

Commit d5560b2

Browse files
committed
Refactor the build_all_series function to treat the history array as an async stream
1 parent 9a5de59 commit d5560b2

1 file changed

Lines changed: 31 additions & 11 deletions

File tree

  • lib/ex_finance_web/live/public/currency_live

lib/ex_finance_web/live/public/currency_live/show.ex

Lines changed: 31 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ defmodule ExFinanceWeb.Public.CurrencyLive.Show do
4343
socket.assigns.interval
4444
) do
4545
all_series =
46-
build_all_series(
46+
build_all_series_async(
4747
socket.assigns.currencies
4848
|> Enum.filter(&(&1.id != socket.assigns.currency.id)),
4949
socket.assigns.interval
@@ -121,16 +121,36 @@ defmodule ExFinanceWeb.Public.CurrencyLive.Show do
121121
defp assign_interval(socket, interval \\ :daily),
122122
do: assign(socket, :interval, interval)
123123

124-
defp build_all_series(currencies, interval) do
125-
Enum.map(currencies, fn %Currency{
126-
type: type,
127-
supplier_name: supplier_name
128-
} = currency ->
129-
with {:ok, history} <-
130-
Currencies.fetch_currency_history(supplier_name, type, interval) do
131-
build_dataset(currency, history, by: :type)
132-
end
133-
end)
124+
@spec build_all_series_async(
125+
[Currency.t()],
126+
Currencies.interval()
127+
) :: [[map()]]
128+
defp build_all_series_async(currencies, interval) do
129+
start_time = System.monotonic_time()
130+
131+
result =
132+
Task.async_stream(currencies, fn %Currency{
133+
type: type,
134+
supplier_name: supplier_name
135+
} = currency ->
136+
with {:ok, history} <-
137+
Currencies.fetch_currency_history(
138+
supplier_name,
139+
type,
140+
interval
141+
) do
142+
build_dataset(currency, history, by: :type)
143+
end
144+
end)
145+
|> Enum.map(fn {:ok, result} -> result end)
146+
147+
end_time = System.monotonic_time()
148+
149+
duration =
150+
System.convert_time_unit(end_time - start_time, :native, :millisecond)
151+
152+
Logger.info("Built all series asynchronously in #{duration} ms")
153+
result
134154
end
135155

136156
@spec build_dataset(

0 commit comments

Comments
 (0)