Last active
December 23, 2021 19:48
-
-
Save PJUllrich/6e3ddd2bcbcb17da07f3e2d2e13624a7 to your computer and use it in GitHub Desktop.
PubSub Library for broadcasting results of Ecto operations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule MyApp.PubSubLib do | |
@moduledoc """ | |
This library implements easy to use Publish-Subscribe functionality. | |
## Usage | |
Use this library with `use MyApp.PubSubLib`. | |
## Example | |
defmodule MyApp.MyPublishingModule do | |
use MyApp.PubSubLib | |
def example() do | |
notify_subscribers({:ok, "my value"}, [:my_topic, :my_sub_topic] | |
end | |
end | |
defmodule MyApp.MySubscribingModule do | |
def example() do | |
MyApp.MyPublishingModule.subscribe() | |
end | |
def handle_info({"MyApp.MyPublishingModule", [:my_topic, :my_sub_topic], my_value}, socket) do | |
# ... | |
end | |
end | |
""" | |
defmacro __using__(_) do | |
quote do | |
def topic do | |
inspect(__MODULE__) | |
end | |
def subscribe do | |
Phoenix.PubSub.subscribe(MyApp.PubSub, topic()) | |
end | |
def subscribe(id) do | |
Phoenix.PubSub.subscribe(MyApp.PubSub, topic() <> "#{id}") | |
end | |
def unsubscribe do | |
Phoenix.PubSub.unsubscribe(MyApp.PubSub, topic()) | |
end | |
def unsubscribe(id) do | |
Phoenix.PubSub.unsubscribe(MyApp.PubSub, topic() <> "#{id}") | |
end | |
def notify_subscribers({:ok, schema}, event) do | |
broadcast(schema, event) | |
broadcast(schema, event, schema.id) | |
{:ok, schema} | |
end | |
def notify_subscribers({:error, reason}, _event), do: {:error, reason} | |
defp broadcast(payload, event) do | |
Phoenix.PubSub.broadcast(MyApp.PubSub, topic(), {topic(), event, payload}) | |
end | |
defp broadcast(payload, event, id) do | |
Phoenix.PubSub.broadcast( | |
MyApp.PubSub, | |
topic() <> "#{id}", | |
{topic(), event, payload} | |
) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment