Real-world examples showing how to use the OddSockets Elixir SDK with Elixir/OTP patterns
Run Basic Example# Start a client
{:ok, client} = OddSockets.start_link(api_key: "ak_live_1234567890abcdef")
# Get a channel
channel = OddSockets.channel(client, "my-channel")
# Subscribe to messages
:ok = OddSockets.Channel.subscribe(channel, fn message ->
IO.inspect(message, label: "Received")
end)
# Publish a message
{:ok, result} = OddSockets.Channel.publish(channel, %{text: "Hello World!"})
defmodule MyApp.ChatServer do
use GenServer
def start_link(opts) do
GenServer.start_link(__MODULE__, opts, name: __MODULE__)
end
def init(_opts) do
{:ok, client} = OddSockets.start_link(api_key: "your-api-key")
channel = OddSockets.channel(client, "chat-room")
:ok = OddSockets.Channel.subscribe(channel, &handle_message/1)
{:ok, %{client: client, channel: channel}}
end
defp handle_message(message) do
IO.puts("Chat message: #{inspect(message)}")
end
end
defmodule MyAppWeb.ChatLive do
use MyAppWeb, :live_view
def mount(_params, _session, socket) do
{:ok, client} = OddSockets.start_link(api_key: "your-api-key")
channel = OddSockets.channel(client, "chat-room")
:ok = OddSockets.Channel.subscribe(channel, fn message ->
send(self(), {:new_message, message})
end)
{:ok, assign(socket, client: client, channel: channel, messages: [])}
end
def handle_info({:new_message, message}, socket) do
messages = [message | socket.assigns.messages]
{:noreply, assign(socket, messages: messages)}
end
end
defmodule MyApp.Application do
use Application
def start(_type, _args) do
children = [
# Start OddSockets client as part of supervision tree
{OddSockets, api_key: "your-api-key", name: MyApp.OddSocketsClient},
# Other supervised processes
MyApp.Repo,
MyAppWeb.Endpoint,
{MyApp.ChatManager, []}
]
opts = [strategy: :one_for_one, name: MyApp.Supervisor]
Supervisor.start_link(children, opts)
end
end
defmodule MyApp.MessageProcessor do
def start_processing(api_key) do
{:ok, client} = OddSockets.start_link(api_key: api_key)
channel = OddSockets.channel(client, "processing-queue")
# Use Agent to store state
{:ok, agent} = Agent.start_link(fn -> %{processed: 0, errors: 0} end)
# Subscribe with async processing
:ok = OddSockets.Channel.subscribe(channel, fn message ->
Task.start(fn ->
process_message_async(message, agent)
end)
end)
{:ok, {client, channel, agent}}
end
end
# Subscribe to client events
:ok = OddSockets.subscribe_events(client)
# Handle events in your process
receive do
{:oddsockets_event, :connected} ->
IO.puts("Connected to OddSockets!")
{:oddsockets_event, {:error, reason}} ->
IO.puts("Connection error: #{inspect(reason)}")
{:oddsockets_event, {:worker_assigned, info}} ->
IO.puts("Assigned to worker: #{info.worker_id}")
{:oddsockets_event, :max_reconnect_attempts_reached} ->
IO.puts("Max reconnect attempts reached")
end