I am interested in using an observable to communicate "exceptional states" to different parts of my Angular application, but I am struggling to grasp their functionality.
In the code snippet below, I have created an observer object and turned it into an observable. My goal is to learn how to invoke the "next" method outside the Observable.create method so I can inject custom events into the stream. Trying to call next directly on the observer doesn't seem to provide the solution.
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 particular code snippet generates the following console output:
This is the subscription: Some foo
This is the subscription: Other foo
last value: This is a late breaking value
It appears that calling next
directly on the observer object (which I attempted within the timeout function at the end) does not deliver a value within the subscription.
It is evident that I am struggling to understand the intended functionality of observables. I would appreciate clarity on how to manually insert data into the stream when working with an observable and how subscribers can pick up such data. While I can see how event-driven actions like mouse clicks or AJAX requests trigger this, I am specifically looking to create a stream that can dynamically receive input when specific events occur at various points in my code.