我有一个简单的GenServer,它是:
发电机服务器:
defmodule MyApp.ScoreTableQueue do
use GenServer
@impl true
def init(stack) do
{:ok, stack}
end
@impl true
def handle_call(:pop, _from, state) do
{:reply, state, []}
end
@impl true
def handle_cast({:push, item}, state) do
{:noreply, [item | state]}
end
end
模块:
defp order_score(question, season) do
for team <- season.teams do
state = score_table_map(question, team)
# Push state on GenServer queue
end
create_score_table(question, season)
end
defp score_table_map(question, team) do
p_score = Enum.find(team.prediction_scores, &(&1.question_id == question.id))
%{team_score: p_score.score, team_id: p_score.team_id}
end
defp create_score_table(question, season) do
changeset = ScoreTable.changeset(%ScoreTable{
question_id: question.id,
season_id: season.id,
table_details: %{
information: # Pop state of genserver
}
})
Repo.insert(changeset)
end
正如在代码示例中指出的,我想在GenServer上的循环期间推送一些状态,然后我想在下面的变更集中弹出状态。
我的主要问题是如何在另一个模块中初始化genserver,这是最佳实践吗?