IT이야기

rx.js가 있는 배열의 추가 사항을 관찰할 수 있는가?

cyworld 2022. 3. 16. 22:04
반응형

rx.js가 있는 배열의 추가 사항을 관찰할 수 있는가?

fromArray Rx wiki on Github.

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함수는 한 번만 발사된다.내가 배열의 변화를 관찰하지 않고 배열 하나하나를 관찰하는 것이기 때문에, 그것은 약간 잘못된 표현인 것 같다.하지만 그 코드는 위키에 나오는 것과 거의 똑같다.그래서 내가 잘못하고 있거나 아니면 잘못하고 있다.subscribe내 예상대로 되지 않아

RxJS에서는 당신이 찾고 있는 것을 a라고 부른다.Subject그 안으로 데이터를 밀어넣고 거기서 스트리밍할 수 있다.

예:

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));

Rx를 찾았어.관측 가능.ObjectChanges(obj)가 예상한 대로 작동함.

설명서 페이지에서:

Object.observe를 사용하여 객체의 변경으로부터 관측 가능한 시퀀스를 작성한다.

도움이 되길 바래.

이거 어때:

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']);

관측할 수 있다.fromArray는 구독자를 추가할 때 각 배열 항목에 대한 이벤트를 즉시 실행하는 관찰 가능을 생성한다.따라서, 그것은 그 배열의 변화를 "관찰"하지 않을 것이다.

만약 당신이 "밀 수 있는 수집품"이 필요하다면, Bacon.js의 버스 클래스가 당신이 찾고 있는 것일지도 모른다.RxJ의 경우 비슷한 기능을 가진 MessageQueue 클래스가 있다.

참조URL: https://stackoverflow.com/questions/14466285/can-i-observe-additions-to-an-array-with-rx-js

반응형