问题描述
coffee> rext = require 'rx'
coffee> arr = [1..5]
[ 1, 2, 3, 4, 5 ]
coffee> obs = rext.Observable.fromArray(arr)
{ _subscribe: [Function] }
coffee> obs.subscribe( (x) -> console.log("added value: " + x))
added value: 1
added value: 2
added value: 3
added value: 4
added value: 5
{ isStopped: true,
observer:
{ isStopped: true,
_onNext: [Function],
_onError: [Function: defaultError],
_onCompleted: [Function: noop] },
m: { isDisposed: true, current: null } }
coffee> arr.push(12) # expecting "added value: 12"
6 # instead got new length of array
coffee>
实际上,subscribe
函数在创建时仅会触发一次.似乎有点用词不当,因为我实际上只是为每个数组而不是观察数组上的更改.该代码几乎与Wiki上的完全相同.因此,要么我做错了,要么subscribe
不能按我预期的那样工作.
It really looks like the subscribe
function will only fire one time, when it's created. It seems like it's a bit of a misnomer, since I'm really just for-eaching the array instead of observing changes on it. That code is almost exactly the same as what's on the wiki though. So either I'm doing it wrong or the subscribe
doesn't work how I expect.
推荐答案
Observable.fromArray创建一个Observable,当您添加订阅服务器时,该Observable立即为每个数组项触发事件.因此,它不会监视"对该数组的更改.
Observable.fromArray creates an Observable that immediately fires events for each array items, when you add a Subscriber. So, it won't be "watching" the changes to that array.
如果您需要可推送集合",则 Bacon.js 中的Bus类可能是您正在寻找什么.对于RxJ,有一个我的小 MessageQueue 类,它具有类似的类功能.
If you need a "pushable collection", the Bus class in Bacon.js might be what you're looking for. For RxJs there's my little MessageQueue class that has a similar functionality.
这篇关于我可以通过rx.js观察到数组的附加内容吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!