Rails [求助] 关于 ActionCable 中 stream_from stream_for 函数的作用

lilijreey · 2016年08月06日 · 最后由 lilijreey 回复于 2016年08月09日 · 2776 次阅读

请问这俩函数是干啥用的?看了半天文档没搞清楚用途。 Doc http://edgeapi.rubyonrails.org/classes/ActionCable/Channel/Streams.html#method-i-stream_for

class CommentsChannel < ApplicationCable::Channel
  def follow(data)
    stream_from "comments_for_#{data['recording_id']}"
  end

  def unfollow
    stop_all_streams
  end
end

class CommentsChannel < ApplicationCable::Channel
  def subscribed
    post = Post.find(params[:id])
    stream_for post
  end
end


stream_for第一个参数是 model, stream_from第一个参数是 channel 的名字

实际写一下 code 被坑一次就大概了解了。每当有从 client 来的请求,相对的 server side 的 handler method 需要给这些请求一个标记。用来标记这些 request 的就是 stream_for 和 stream_from。

比如在/post/1,某用户回复了该文章,我们需要对在浏览该文章的所有 client 更新回复的列表,我们可以用 stream_for post这种形式,其中 post 是 Post Model 的一个 instance。当然,如果还可以自己设定一种标记,比如update_post_#{data[:id]}这种,这里的 id 则是 post 的 id,这样的话就需要用 stream_from 这种形式。

stream_for 只是一个方便的写法,方便根据 model 生成 channel name,底层调用的还是 stream_from 。我大部分时候都用的 stream_from ,因为构造的 channel name 都不大规则……

stream_from 和 stream_for 都是用来标记某条连接下面的某个 stream。ActionCable 收发信息的最小单位是 stream。

stream_from 的参数要跟 ActionCable.server.broadcast 的第一个参数一致,这样前端才能收到广播

你在 app/assets/javascripts/cable.js 里面加一行代码启用 debug

App.cable = ActionCable.createConsumer();
ActionCable.startDebugging(); // 启用调试

,然后动手试试,看打印信息就知道,再不行就看源码。

stream_for 先把 channel 和 model 的信息拼凑成字符串(具体什么形式不清楚)作为参数,然后调用 stream_from

需要 登录 后方可回复, 如果你还没有账号请 注册新账号