javascript - Using RxJs Observables - why isn't the subscriber notified when data changes? -
https://plnkr.co/edit/rfmcrn9ef3abivgdezsi?p=preview
in simple example, set observable , subscriber. when push new item ("labrador retriever") array, expected subscriber notified.. not case..
what missing here??
const dogbreeds = ['hound', 'dachshund', 'pekingnese', 'pug', 'mastiff']; settimeout(() => { dogbreeds.push('labrador retriever'); }, 1000); const dogbreedobservable = rx.observable.from(dogbreeds); const dogbreedsubscriber = dogbreedobservable .subscribe( onnext, function onerror(err) { console.log('error: ' + err); }, function oncompleted() { console.log('no more breeds!'); } ); function onnext(breed) { console.log('breed: ' + breed); console.log(dogbreeds); }
you've created stream of dogbreeds
when still haven't added values. subsequetial changes dogbreeds
not emit, because you've never told so.
what should create subject. since want starting value, might interested in behaviorsubject
. need emit new value, demo, might following.
settimeout(() => { this.dogbreeds = [...this.dogbreeds, 'new', 'breed'] dogbreedobservable.next(this.dogbreeds) }, 10)
however, if want in more rxjs-like-way, should consider using operator such [scan
] (http://reactivex.io/rxjs/class/es6/observable.js~observable.html#instance-method-scan) keep accumulated values of breeds on each new breed want add.
Comments
Post a Comment