Reputation: 1501
When generating a new channel, there is commented out stream_from method call. I understand, that it suits for recognizing streams, like stream_from "comments_#{message.id}".
But if this channel has no such goal and should stream all comments? What is default behavior (of value maybe) of this channel without specifying stream_from?
Upvotes: 0
Views: 167
Reputation: 6603
Asssuming that your channel is named SomethingChannel
class SomethingChannel < ApplicationCable::Channel
def subscribed
# because you do not need stream_from, then remove the stream_from below
# stream_from "something_channel"
# and just immediately transmit the data. This should be a hash, and thus I use `as_json`; Change this accordingly as you see fit
transmit(Comment.all.as_json)
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
end
Then on the client-side, you just simply invoke the following whenever you already need this.
# ...coffee
App.cable.subscriptions.create 'SomethingChannel',
connected: ->
console.log('connected')
# Called when the WebSocket connection is closed.
disconnected: ->
console.log('disconnected')
# `transmit(Comment.all.as_json)` above will invoke this
received: (data) ->
console.log('received')
console.log(data)
You should see the something like the following in your Google Chrome / Firefox console:
connected
received
▼ [{…}]
▶ 0: {id: 1, title: "Hello ", content: "World from Earth! :)", created_at: "2018-02-13T16:15:05.734Z", updated_at: "2018-02-13T16:15:05.734Z"}
▶ 1: {id: 2, title: "Lorem ", content: "Ipsum Dolor", created_at: "2018-02-13T16:15:05.734Z", updated_at: "2018-02-13T16:15:05.734Z"}
length: 2
▶ __proto__: Array(0)
P.S. if you are not gonna make use of stream_from
or stream_for
then perhaps you might not need ActionCable
after all, and perhaps you'd be better off retrieving all the comments from an API instead (i.e. GET /comments
)
Upvotes: 1