Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support custom state for event handlers #400

Merged
merged 2 commits into from
Aug 16, 2020

Conversation

slashdotdash
Copy link
Member

An event handler can define and update custom state which is held in the GenServer process' memory. It is passed to the handle/2 function as part of the metadata using the :state key. The state is transient and will be lost whenever the process restarts.

Initial state can be set in the init/1 callback function by adding a :state key to the config. It can also be provided when starting the handler process:

ExampleHandler.start_link(state: initial_state)

Or when supervised:

Supervisor.start_link([
  {ExampleHandler, state: initial_state}
], strategy: :one_for_one)

State can be updated by returning {:ok, new_state} from any handle/2 function. Returning an :ok reply will keep the state unchanged.

Handler state is also included in the Commanded.Event.FailureContext struct passed to the error/3 callback function.

Example

defmodule StatefulEventHandler do
  use Commanded.Event.Handler,
    application: ExampleApp,
    name: __MODULE__

  def init(config) do
    config = Keyword.put_new(config, :state, %{})

    {:ok, config}
  end

  def handle(event, metadata) do
    %{state: state} = metadata

    new_state = mutate_state(state)

    {:ok, new_state}
  end
end

Closes #366.

Allow event handlers to manage custom in-memory process state which can be read and updated in the `handle/2` callback function.
@slashdotdash slashdotdash force-pushed the feature/event-handler-state branch from cd05841 to a79f65b Compare August 16, 2020 17:14
@slashdotdash slashdotdash merged commit 72fea92 into master Aug 16, 2020
@slashdotdash slashdotdash deleted the feature/event-handler-state branch August 16, 2020 19:18
@larskluge
Copy link
Contributor

Awesome, thank you @slashdotdash !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Support Custom State for Event Handlers?
2 participants