...

/

How to Use Anonymous Functions

How to Use Anonymous Functions

Learn to create anonymous functions and explain some callback functions.

Implement handle_continue

We return {:ok, state, {:continue, :run}} from the init/1 callback, so we have to handle this message next. Within the handle_continue/2 callback, we perform the required work as soon as the process finishes initializing:

Press + to interact
#file path -> jobber/lib/jobber/job.ex
def handle_continue(:run, state) do
new_state = state.work.() |> handle_job_result(state)
if new_state.status == "errored" do
Process.send_after(self(), :retry, 5000)
{:noreply, new_state}
else
Logger.info("Job exiting #{state.id}")
{:stop, :normal, new_state}
end
end

Since the work attribute is an anonymous function, we invoke it using the state.work.() syntax and process the result.

We use the status attribute to determine whether or not we need to retry the job. If the status is errored, we schedule another attempt in five seconds and keep the process running. Otherwise, we stop the process for done and failed, since there isn’t any work left to do.

Handle the result

We need to consider three different outcomes when handling the result:

  • Success: This is when the job completes and returns {:ok, ...