Elixir foundationSort Order

Elixir: Tracking Responses with an Agent - [020]

In this episode we'll be tracking the responses using the Network.responseReceived event.

We need to start another Agent for tracking responses so in our init callback let's add that in our GenServer

def init(url) do  # ...  {:ok, responses} = Agent.start_link(fn -> [] end)     # ...  :ok = PageSession.subscribe(conn, "Network.responseReceived", self())  # ...  {:ok, %{    conn: conn,     requests: requests,    responses: responses,    origin: "https://www.artellectual.com"  }}end

Let's write the handle_info to handle the event from the Network.responseReceived event.

def handle_info(  {:chrome_remote_interface, "Network.responseReceived", data},   state) do  %{"url" => url, "status" => status} = data["params"]["response"]    if url =~ state.origin do     Agent.update(state.responses, fn state -> state ++ [status] end)  end    {:noreply, state}end

next we'll need to add the api that will allow us to return all the responses

def network_responses(pid) do  GenServer.call(pid, :network_responses)enddef handle_call(:network_responses, _from, state) do  {:reply, Agent.get(state.responses, fn state -> state end), state}end

That's pretty much it! this should be everything in terms of tracking and returning responses.