What is Action cable
Action Cable is a feature of the Ruby on Rails framework that provides real-time, bidirectional communication between a web server and its clients using WebSockets. It allows for the creation of dynamic, interactive user experiences by enabling real-time updates in the browser without the need for a page refresh.
Action Cable works by setting up a persistent connection between the client (typically a web browser) and the server. The client can send messages to the server and receive messages from the server in real-time, which enables real-time updates in the user interface. It provides both client-side JavaScript framework and a server-side Ruby framework.
Create a Client side channel subscription
// app/javascript/channels/chatroom_channel.js
import consumer from "./consumer"
consumer.subscriptions.create({ channel: "ChatRoom", room_id: room_id}, {
connected() {
// Called when the subscription is ready for use on the server
console.log('connected to ChatRoom', room_id)
},
disconnected() {
// Called when the subscription has been terminated by the server
},
received(data) {
// Called when there's incoming data on the websocket for this channel
console.log(data)
}
});
Before
Considering the above example, In the previous versions of Rails,
the connected method is called when the WebSockets connection is established, and the disconnected method is called when the connection is lost
After
Rails 7 has added the ability for subscribers to handle reconnections with the
connected()
callback if they miss some messages due to a lost connection.
// app/javascript/channels/chatroom_channel.js
import consumer from "./consumer"
consumer.subscriptions.create({ channel: "ChatRoom", room_id: room_id}, {
connected({reconnected}) {
// Called when the subscription is ready for use on the server
console.log('connected to ChatRoom', room_id)
if (reconnected) {
console.log('reconnected to ChatRoom', room_id)
}
}
});
Check out the PR for more details.