From the Rails Guide I found following three code snippets
ActionCable.server.broadcast("chat_#{params[:room]}", data)
This simple broadcast sends the data to a specific chat room
while broadcast_to
as shown below seems to send data to all chatrooms within a channel to which current user is subscribed .
WebNotificationsChannel.broadcast_to(
current_user,
title: 'New things!',
body: 'All the news fit to print'
)
Here is another type of broadcast broadcast_for - for which i couldn't get any example .
My question is what is actual difference between these three and when to use each of 'em - thanks in advance
broadcasting_for
returns an object that can be reused. This is useful for sending multiple messages to the same room in different points in code / time. broadcast
ends up calling broadcasting_for
, so it's basically the same.
broadcast_to
comes off the channel class. You use this after you've created a channel. Let's say you want to notify all the subscribers of blog post comments. Then your channel would look like the example:
class CommentsChannel < ApplicationCable::Channel
def subscribed
post = Post.find(params[:id])
stream_for post
end
end
# use CommentsChannel.broadcast_to(@post, @comment)
But if you wanted to send more directed messages to a particular user then you could have a class called EmailNotifications
that only cares about a particular user.
class EmailNotificationsChannel < ApplicationCable::Channel
...
EmailNotificationsChannel.broadcast_to(
current_user,
title: 'You have mail!',
body: data[:email_preview] # some assumption of passed in or existing data hash here
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With