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

[Recipe] Transient subscription #17

Open
slashdotdash opened this issue Oct 19, 2020 · 0 comments
Open

[Recipe] Transient subscription #17

slashdotdash opened this issue Oct 19, 2020 · 0 comments

Comments

@slashdotdash
Copy link
Member

slashdotdash commented Oct 19, 2020

How to create a transient subscription to a stream, or all streams, and wait until an expected event is received.

Use Commanded.EventStore.subscribe/2 as shown in the following example.

alias Commanded.EventStore.RecordedEvent

defp receive_events(selector) do
  receive do
    {:events, events} ->
      case reduce(events, selector) do
        :cont -> receive_events(selector)
        {:halt, result} -> result
      end
  end
end

defp reduce([], _selector), do: :cont

defp reduce([%RecordedEvent{data: data} | events], selector) do
  case selector.(data) do
    :cont -> reduce(events, selector)
    {:halt, result} -> {:halt, result}
  end
end

Usage

:ok = Commanded.EventStore.subscribe(MyApp.App, stream_uuid)

receive_events(fn 
  %AnEvent{} = event -> {:halt, event}
  _event -> :cont
end)

Use :all as the stream identity to subscribe to all events.

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

No branches or pull requests

1 participant