Difference between broadcast , broadcast_to and broadcast_for in rails 5
Asked Answered
B

1

10

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

Bushel answered 23/1, 2017 at 12:51 Comment(0)
L
4

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
)
Lumper answered 27/4, 2017 at 23:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.