客户取消订阅频道

时间:2016-03-03 17:42:44

标签: ruby-on-rails actioncable

是否可以将未订阅的频道“名称”返回到未订阅的方法?

当用户取消订阅某个频道时(由于断开连接或离开),我需要确保将客户端标志设置为空状态。我已经创建了一个清理方法,但是我无法找出应该将清理消息发送到哪个通道..因为我无法获得从哪个通道调用未订阅的方法。

class ConversationChannel < ApplicationCable::Channel
  def follow(data)
    stop_all_streams
    conversation = Conversation.find(data['conversation_id'])
    if conversation.is_participant?(current_user)
      stream_from "conversation:#{data['conversation_id']}"
    end
  end

  def unsubscribed
    clear_typing
  end

  ...

  def clear_typing
    # need way to find out conversation_id of the unsubscribed stream
    ActionCable.server.broadcast "conversation:#{data['conversation_id']}", {id: current_user.id, typing: false}
  end
end

2 个答案:

答案 0 :(得分:1)

我认为班级名称是频道名称。

来自ActionCable文档:

# app/channels/appearance_channel.rb
class AppearanceChannel < ApplicationCable::Channel
  def subscribed
    current_user.appear
  end

  def unsubscribed
    current_user.disappear
  end

  def appear(data)
    current_user.appear on: data['appearing_on']
  end

  def away
    current_user.away
  end
end

客户订阅如下:

# app/assets/javascripts/cable/subscriptions/appearance.coffee
App.cable.subscriptions.create "AppearanceChannel",
  # Called when the subscription is ready for use on the server
  connected: ->
    @install()
    @appear()

  # Called when the WebSocket connection is closed
  disconnected: ->
    @uninstall()

  # Called when the subscription is rejected by the server
  rejected: ->
    @uninstall()

  appear: ->
    # Calls `AppearanceChannel#appear(data)` on the server
    @perform("appear", appearing_on: $("main").data("appearing-on"))

  away: ->
    # Calls `AppearanceChannel#away` on the server
    @perform("away")


  buttonSelector = "[data-behavior~=appear_away]"

  install: ->
    $(document).on "page:change.appearance", =>
      @appear()

    $(document).on "click.appearance", buttonSelector, =>
      @away()
      false

    $(buttonSelector).show()

  uninstall: ->
    $(document).off(".appearance")
    $(buttonSelector).hide()

如果你仔细观察,客户正在订阅频道AppearanceChannel,这是该类的名称。

答案 1 :(得分:1)

我认为这是一个可行的解决方案,但如果可能的话我可以抓住确切的未订阅的流会更好:

通过查看stop_all_streams方法找到了这个,因为它提醒我存在'streams'变量。

...
  def unsubscribed
    streams.each do |stream|
      ActionCable.server.broadcast stream[0], {id: current_user.id, typing: false}
    end
  end
...