I learned a lot by looking at the ActionCable example . I, too, was embarrassed by the documents that offer parsing options and start streaming playback immediately by subscription. Although this is an option , you may prefer the approach below.
Create a special method that can be called from the client side (JS), for example start_listening :
class RoomChannel < ApplicationCable::Channel
With this code (and server restart) you can now call the following line when you really loaded the room:
App.roomChannel.perform("start_listening", {room_id: 20});
Now you can transfer data to the room anywhere using broadcast_to . For instance. from RoomMessage after_safe -action:
RoomChannel.broadcast_to(room, room_message)
This will send a message to everyone who is listening.
Separating the moment you start listening to a stream from the actual opening of the connection, it is easier to configure several data streams (there is one connection that can have many channels, which can have many streams) (just do not close the old streams when starting a new one;)). The connection setup time will also be a little faster, although this is usually due to the price of having an open connection, possibly after the user logs in, which you can easily bypass by signing up immediately before listening.
source share