Can I observe additions to an array with rx.js?

前端 未结 4 1477
梦如初夏
梦如初夏 2020-12-30 00:34

fromArray Rx wiki on github

coffee> rext = require \'rx\'                                                 
coffee> arr = [1..5]                                 


        
相关标签:
4条回答
  • 2020-12-30 00:47

    I found Rx.Observable.ofObjectChanges(obj) to work just as I expected.

    From the documentation page:

    Creates an Observable sequence from changes to an object using Object.observe.

    Hope it helps.

    0 讨论(0)
  • 2020-12-30 00:55

    How about this:

    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']);
    
    0 讨论(0)
  • 2020-12-30 01:02

    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.

    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.

    0 讨论(0)
  • 2020-12-30 01:02

    In RxJS what you are looking for is called a Subject. You can push data into it and stream it from there.

    • Subject getting started guide
    • Subject API docs.

    Example:

    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));
    
    0 讨论(0)
提交回复
热议问题