Suppose I have an Observable that has been created like this
let observable = of(mockData).pipe(delay(5000));
How can I at an later point in time, emit another value to the observers currently subscribing to this observable?
I have read this RxJS: How would I "manually" update an Observable? and BehaviorSubject vs Observable? but I can not seems to grasps why I am holding an object of type Observable in my hand, and can not access any easy way to emit data to observers without defining an emitter independently at the observable creation time like this
var emitter;
var observable = Rx.Observable.create(e => emitter = e);
var observer = {
next: function(next) {
console.log(next);
},
error: function(error) {
console.log(error);
},
complete: function() {
console.log("done");
}
}
observable.subscribe(observer);
emitter.next('foo');
emitter.next('bar');
emitter.next('baz');
emitter.complete();
//console output
//"foo"
//"bar"
//"baz"
//"done"
CodePudding user response:
Observables
are not Emmitables
(not official interface name;P) thus you cannot emmit using Observable
What you have to do is to combine that existing stream with subject that you can use to emmit new values, eg using merge
const subject=new Subject():
const yourObservableThatYouCannotChange;
const combinedObservable=merge(yourObservableThatYouCannotChange,subject);
now you have to return combinedObservable
for others to subscribe to. Then if you want to inject emition into this stream, you simly emit it via subject.next(yourVal)
.
CodePudding user response:
I am not sure I understood your goal correctly, but why not try it like this:
private subject = new Subject();
public observable = this.subject.asObservable();
This way you change your subject with internal methods, the observable will emit every new change, and the subject itself will be protected while you can only subscribe to the observable.