I would like to use an observable to signal various parts of my Angular application about "exceptional states" and likewise, but I realize I don't really understand how they work.
In the following code, I built an observer object, and created an observable from it. What I would like to do is figure out how to call the "next" method outside the scope of the Observable.create method so I can insert arbitrary events into the stream. Calling next directly on the observer deosn't seem to be the answer.
var observer = {
next: function(value) {
this.myvalue="last value: " + value;
},
error: function(error) {
console.log(error);
},
complete: function() {
console.log('completed');
},
myfunction: function() {
this.myvalue = "Penguins"
},
myvalue: ""
}
let myobs$ : Observable<any> = Observable.create(function(obs) {
obs.next("Some foo");
obs.next("Other foo");
})
let foo=myobs$.subscribe((observer)=> {
console.log("This is the subscription: ", observer)
})
setTimeout(function() {
observer.next("This is a late breaking value");
console.log(observer.myvalue);
}, 2000);
}
this code produces the following console output:
This is the subscription: Some foo
This is the subscription: Other foo
last value: This is a late breaking value
So it looks like calling next
on the observer object directly (which I tried inside of the timeout function at the bottom) doesn't produce a value inside the subscription.
Also clear I guess that I don't understand how these things are supposed to work. It would be helpful to understand that if I set up an observerable and I want to 'manually' insert data into the stream to be picked up by subscribers, how exactly do I do that? I can see how you do it with event-propagating things like mouse clicks or ajax requests, but what I'm looking to do is create a stream that I can feed on an ad-hoc basis when certain interesting things happen in various places in my code.