我可以观察补充与rx.js数组?(Can I observe additions to an arr

2019-08-07 20:51发布

在github上fromArray的Rx维基

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功能才会触发一次,在创建时。 看起来这是一个有点用词不当,因为我真的只是换eaching的阵列,而不是观察它的变化。 这代码几乎是完全一样的维基,虽然什么。 因此,无论我做错了或subscribe不工作我如何期望。

Answer 1:

Observable.fromArray创建一个可观察的瞬间触发事件为每个阵列的项目,当您添加一个用户。 因此,它不会是“看”的转变,以该数组。

如果你需要一个“被按压集”,中通客车类Bacon.js可能是你在找什么。 对于RxJs有我的小的MessageQueue具有类似的功能类。



Answer 2:

在RxJS你正在寻找被称为Subject 。 您可以将数据推到它,并从那里流呢。

  • 除入门指南
  • 主题API文档 。

例:

var array = [];
var arraySubject = new Rx.Subject();

var pushToArray = function (item) {
  array.push(item);
  arraySubject.next(item);
}

// Subscribe to the subject to react to changes
arraySubject.subscribe((item) => console.log(item));


Answer 3:

我发现Rx.Observable.ofObjectChanges(OBJ) ,只是如我所料工作。

从文档页面:

创建使用Object.observe改变的对象的可观察序列。

希望能帮助到你。



Answer 4:

这个怎么样:

var subject = new Rx.Subject();
//scan example building an array over time
var example = subject.scan((acc, curr) => { 
    return acc.concat(curr);
}
,[]);

//log accumulated values
var subscribe = example.subscribe(val => 
    console.log('Accumulated array:', val)
);

//next values into subject
subject.next(['Joe']);
subject.next(['Jim']);


文章来源: Can I observe additions to an array with rx.js?