Im working through the basics of observables [here][1]
The examples here show Observasbles as functions with multiple returns e.g.
import { Observable } from 'rxjs';
const foo = new Observable(subscriber => {
console.log('Hello');
subscriber.next(42);
subscriber.next(100); // "return" another value
subscriber.next(200); // "return" yet another
});
foo.subscribe(x => {
console.log(x);
});
// outputs 42, 100, 200
Question: Is it possible to add new values to an observable AFTER it has been created e.g. something like this pseudo code:
import { Observable } from 'rxjs';
const foo = new Observable(subscriber => {
subscriber.next(200);
});
// this is pseudocode so wont work, but is the basis of this post.
...
foo.next(400);
...
foo.subscribe(x => {
console.log(x);
});
// is it possible to output 200 and 400 by calling next after instantiation?
Or do I need to use a Subject to do that?
You have to use Subject for this. According to documentation
Every Subject is an Observer. It is an object with the methods next(v), error(e), and complete(). To feed a new value to the Subject, just call next(theValue), and it will be multicasted to the Observers registered to listen to the Subject.
Observables do not have the next method so you can not pass values to them.
You need to use Subject or BehaviorSubject. But BehaviorSubject has an initial value, so you can try to do something like this:
var obs = new rxjs.Observable((s) => {
s.next(42);
s.next(100);
});
obs.subscribe(a => console.log(a));
var sub = new rxjs.BehaviorSubject(45);
obs.subscribe(sub);
sub.next('new value');
sub.subscribe(a => console.log(a));
Every Subject is Observable, so you can easily convert Subject to Observable via yourSubject.asObservable().
NOTE: Don't forget to unsubscribe from observable in order to prevent memory leaks.