2016-06-07 65 views
0

我的代码非常依赖用户是否在线。用ActionCable保持用户“在线”

目前我设置ActionCable这样的:

class DriverRequestsChannel < ApplicationCable::Channel 
    def subscribed 
     stream_from "requests_#{current_user.id}" 
    end 

    def unsubscribed 
    current_user.unavailable! if current_user.available? 
    end 
end 

现在我会非常喜欢的覆盖是用户的,而不是刚进入脱机只是关闭浏览器的情况。但是,取消订阅的问题在于它进行页面刷新。所以每次刷新页面时都会触发unsubscribed。因此即使他们认为他们可用,他们也会被视为不可用。

现在关键是可用不是默认的,所以我可以放回去,这是用户选择接收请求的东西。

有没有人有处理这种情况的最佳方法的经验?

回答

0

你不应该只依靠的WebSockets,还放了用户的在线状态到数据库:

1:添加迁移

class AddOnlineToUsers < ActiveRecord::Migration[5.0] 
    def change 
    add_column :users, :online, :boolean, default: false 
    end 
end 

2:添加AppearanceChannel

class AppearanceChannel < ApplicationCable::Channel 
    def subscribed 

    stream_from "appearance_channel" 

    if current_user 

     ActionCable.server.broadcast "appearance_channel", { user: current_user.id, online: :on } 

     current_user.online = true 

     current_user.save! 

    end 


    end 

    def unsubscribed 

    if current_user 

     # Any cleanup needed when channel is unsubscribed 
     ActionCable.server.broadcast "appearance_channel", { user: current_user.id, online: :off } 

     current_user.online = false 

     current_user.save!  

    end 


    end 

end 

现在,您可以保证免受任何偶然的Websockets连接损失。在每个HTML页面刷新做2件事:

  1. 检查数据库的用户在线状态。
  2. 连接到套接字并订阅外观频道。

这样的组合方式可以随时为您提供用户的在线状态。