Action Cable: How to deliver missed chat messages

扶醉桌前 提交于 2020-08-07 05:35:11

问题


What's a good way to deliver missed messages in a chat for instance with Action Cable? Like when you close the laptop and open it again, you are not reloading the page but you may have missed messages

One way would be to do an AJAX call instead using Action Cable but then i would have to duplicate some of the logic that happens when you receive a message. I would like to just reuse Action Cable if possible


回答1:


Store them in the database of course. And load them from the database each time you re-subscribe to Action Cable.




回答2:


I assume you have seen(read_at timestamp) status for each message and your web-socket is not closed(which turning off laptop or closing browser will close it).

I would create background task which checks all subscribed channels for unseen message. Lets say you have channel "message_234" which user is subscribed and there is some messages there which read_at is nil in your table. then broadcast them to your user with your background task. set the timeout for 1 day to not overload it and do the same to your message_notification channel.




回答3:


You could use #transmit to send past message in #subscribed.

Unfortunately this handy method is barely documented and not mentioned in the current edge guide for Action Cable. But should work in all versions since Action Cable was introduced.

Here's an example:

def subscribed
  lobby = Lobby.find(params[:lobby])
  stream_from(stream_name)
  lobby.messages.order(created_at: :asc).each do |message|
    transmit(message.to_json)
  end
end


来源:https://stackoverflow.com/questions/41203781/action-cable-how-to-deliver-missed-chat-messages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!