Reputation: 19
https://plnkr.co/edit/Rfmcrn9Ef3ABiVGDEZSi?p=preview
In this simple example, i set up an observable and a subscriber. When i push a new item ("Labrador Retriever") to the array, I expected the subscriber to be notified.. not the case..
What am I 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);
}
Upvotes: 0
Views: 957
Reputation: 19764
You've created a stream of dogBreeds
as it was when you still haven't added any values. Subsequetial changes to dogBreeds
will not emit, because you've never told it to do so.
What you should do is create a Subject. Since you want a starting value, you might be interested in BehaviorSubject
. What you need to do is to emit a new value, so for your demo, you might do something like the following.
setTimeout(() => {
this.dogBreeds = [...this.dogBreeds, 'new', 'breed']
dogBreedObservable.next(this.dogBreeds)
}, 10)
However, if you just want to do it in a more RxJS-like-way, you should probably consider using operator such as [scan
]
(http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-scan) to keep accumulated values of all breeds on each new breed that you want to add.
Upvotes: 1