axelson
How can you modularize a Phoenix Channel
I’m struggling with how to sustainably organize a Phoenix Channel. Even with the concept/design of “Phoenix Is Not Your Application” I find my channels growing very large as the number of potential messages sent to or from a channel increases.
I’ve sometimes wished for a “routing” mechanism similar to HTTP but specific to a channel. So that certain prefixes of incoming channel messages could be handled in a consistent way. Alternatively I may want to just create more channels to spread out the messages, but then the clients need to join multiple channels when they connect to the socket. Which isn’t a huge burden (and is fine performance-wise since subscriptions are cheap), but feels like unneeded complexity.
How have others tackled this issue? Or is it a non-issue?
Most Liked
axelson
For anyone stumbling on this post now I’d recommend trying out this library that is made to modularize a Phoenix Channel:
chrismccord
Can you share your current channel code? it would be easier to say more if we have a real example to discuss. Thanks!
yurko
With full blown WebSocket APIs I also dislike them getting too big so I split them into sub-channels with a tiny bit of pattern matching, this way I can have the handlers separate (they still don’t do anything but delegate to context services), that keeps the files reasonably small.
Here is an example of a channel that delegates to subtopics:
alias App.Service.Channel.{Faq, Learning, Search} # etc
# join clauses
def handle_in("faq:" <> msg, payload, socket), do: Faq.process_message(msg, payload, socket)
def handle_in("learning:" <> msg, payload, socket), do: Learning.process_message(msg, payload, socket)
def handle_in("search:" <> msg, payload, socket), do: Search.process_message(msg, payload, socket)
# etc
Frontend can then send a message such as search:find with some payload, the channel will process it and call process_message in Search service with find message.
Popular in Questions
Other popular topics
Latest Phoenix Threads
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #hex
- #security









