diff --git a/lib/last_fm/refresh.ex b/lib/last_fm/refresh.ex index bdb39398..e4bd88d0 100644 --- a/lib/last_fm/refresh.ex +++ b/lib/last_fm/refresh.ex @@ -17,10 +17,9 @@ defmodule LastFm.Refresh do GenServer.start_link(__MODULE__, config, name: __MODULE__) end - @spec refresh() :: :refresh + @spec refresh() :: :ok def refresh do - # TODO: Very barebones and naive - can be improved by building a state machine. - send(__MODULE__, :refresh) + GenServer.call(__MODULE__, :refresh) end @impl true @@ -36,24 +35,39 @@ defmodule LastFm.Refresh do end @impl true - @spec handle_continue(atom(), config) :: {:noreply, config} + @spec handle_call(:refresh, GenServer.from(), config) :: + {:reply, :ok | {:error, term()}, config, pos_integer()} + def handle_call(:refresh, _from, config) do + case config.api.get_recent_tracks(config.user, config.api_key) do + {:ok, tracks} -> + Feed.update(tracks) + {:reply, :ok, config, config.refresh_interval} + + error -> + # TODO: think about failure scenario - error is logged at the API level + {:reply, error, config, config.refresh_interval} + end + end + + @impl true + @spec handle_continue(atom(), config) :: {:noreply, config, pos_integer()} def handle_continue(:refresh, config), do: refresh(config) @impl true - @spec handle_info(atom(), config) :: {:noreply, config} + @spec handle_info(atom(), config) :: {:noreply, config, pos_integer()} def handle_info(:refresh, config), do: refresh(config) + def handle_info(:timeout, config), do: refresh(config) + defp refresh(config) do case config.api.get_recent_tracks(config.user, config.api_key) do {:ok, tracks} -> Feed.update(tracks) - Process.send_after(self(), :refresh, config.refresh_interval) - {:noreply, config} + {:noreply, config, config.refresh_interval} {:error, _reason} -> # TODO: think about failure scenario - error is logged at the API level - Process.send_after(self(), :refresh, config.refresh_interval) - {:noreply, config} + {:noreply, config, config.refresh_interval} end end