Hello,
I want to start a module (MyApp.MyAgent
) using Agent
that will fetch some data from DB (and thus use MyApp.Repo
) and keep it in memory, and I want the data to be available when the application starts. So I add it as a child to the superviser but the compiler complains that MyApp.Repo
has not yet been started when aliasing it in MyApp.MyAgent
:
def start(_type, _args) do
# List all child processes to be supervised
children = [
# Start the Ecto repository
MyApp.Repo,
# Start the endpoint when the application starts
MyAppWeb.Endpoint,
# Starts a worker by calling: MyApp.Worker.start_link(arg)
# {MyApp.Worker, arg},
MyApp.MyAgent.start_link()
]
defmodule MyApp.MyAgent do
import Ecto.Query, warn: false
alias MyApp.Repo
alias MyApp.SomeContext.SomeSchema
def start_link do
ids = Repo.all(from s in SomeSchema, select: s.id)
Agent.start_link(fn -> ids end, name: __MODULE__)
end
def all do
Agent.get(__MODULE__, & &1)
end
end
Thank you for any help!