Stimulus and ActionCable
Learn about using Stimulus with ActionCable on the client-side.
The Turbo ActionCable helpers are useful, but they don’t cover every use case for ActionCable. We may need to use ActionCable by using custom JavaScript on the client, either because there is an already existing endpoint or because our task doesn’t quite fit the Turbo patterns. In this lesson, we’re going to use ActionCable to rebuild the “sold out” feature we previously built using polling in.
To use ActionCable directly, we need to create objects on the client and the server.
ActionCable on the server-side
On the server, we have channels and connections.
ActionCable channel
An ActionCable channel is roughly analogous to a Rails controller. The channel is where we put the code that responds to data the server receives over the socket and where we set up the structure of the data being sent to the client. Turbo created a generic channel for us to use, but we’re going to build a custom one.
ActionCable connection
The connection class is more abstract. It’s used by the channel and typically handles authorization. In setting up our project, Rails created the two top-level classes, ApplicationCable::Connection
and ApplicationCable::Channel
, that we can use as base classes.
ActionCable on the client-side
On the client-side, we’ll call a method called createConsumer
that returns a data object that we can use to subscribe to a specific server-side channel, and then specify what we want to happen in response to received data.
Using ActionCable
Let’s look at an example of using ActionCable to broadcast sold-out concert ...