0

I want to use Action Cable (Rails 5) to create a chat app.

When the client signs in to the app, I send the message to subscribe for the channel. The channel will stream for connection based on current_user 's room_id. When the user sends a message it will be sent to all who subscribed for the channel That 's normal flow of action cable.

Here is my channel:

class RoomChannel < ApplicationCable::Channel
  def subscribed
   current_user.chatrooms.each do |chatroom|
       stream_from "room_#{chatroom.id}"
   end
 end
end

But I wonder when the client sends the message to the new one who is not in the room. The streaming was not created. How can the other receive the message and keep the conversation move on?

Amir
  • 16,067
  • 10
  • 80
  • 119
lin
  • 1
  • 1
  • 2

1 Answers1

0

For a user who is sending the message, you can create a callback in your message model that broadcasts to your channel when a message is created. I assume you created correct associations. i.e Rooms has_many messages. Message in turn belongs_to Room and User Something like this:

class Message < ApplicationRecord
    after_create :broadcast_to_room
    .......
    private
    def broadcast_to_room
        @room = self.room
        RoomChannel.broadcast_to(@room, message: self)
    end
    .........
end

So whenever a message is created, it is broadcasted to the room the message belongs to. Your RoomChannel can be like this:

class RoomChannel < ApplicationCable::Channel
    def subscribed
        room = Room.find(params[:id])
        stream_for room
    end
end

Now in the from facing page of the room, you should have a function that subscribes to listen for incoming messages. So when a message comes in, your listener picks up the message and displays it. I wrote a gist here on how you can use actioncable in a client (in react-native). In your client you create a socket that listens for incoming messages.

LordKiz
  • 603
  • 6
  • 15
  • Thanks for your answer, LordKiz. I am using Android as my client. As my query is at the time the channel broadcast the message. Cause this is the first time two user start to chat together, the room has just created (room_id not existed in the database) and it is not streaming on the server. That mean client didn't subcribe for that stream and cannot receive the incoming message. – lin Sep 18 '18 at 03:57
  • Exactly. If client is not subscribed, it is impossible to receive incoming messages. You should create a room with an id in your database when two users start a chat. And stream to that room. – LordKiz Sep 18 '18 at 07:36
  • So in this case, client needs to send the request to re-subscribe channel, right? or do something to stream to that room on the server? I still don't know how to hande this. – lin Sep 18 '18 at 09:42
  • Yea. Everytime client opens that room, create a socket that subscribes to the channel. – LordKiz Sep 18 '18 at 12:51