I'm an absolute rxjs beginner. For me to start learning to think in observables, I need to translate concepts through code examples. I feel like if I can see the code for this, I can start to do this on my own with other concepts.
I do NOT want to CONVERT a promise to an observable, I want to make a new implementation using Observable that can behave like a promise. How would I re-write the following using Observables?
constructor(){
let makeMessage2 = function(){
return new Promise(resolve, reject){
setTimeout(()=>{
var r = Math.random();
resolve("message two plus random value: " + r );
}, 1000);
}
}
this.logMessageAndResultOfCallback("message one!", makeMessage2);
}
private sideEffect1:string = "";
private sideEffect2:string = "";
logMessageAndResultOfCallback( message1:string, callback:Function ){
console.log(message1);
this.sideEffect1 = message1;
callback().then((message2)=>{
console.log(message2);
this.sideEffect2 = message2;
}
}
I guess the part I don't understand is how to define the "callback" function, how to invoke it. I understand I would wait for the complete or emit handlers, like makeMessage2().subscribe(message2 => console.log(message2));
but I don't have any clue how to define makeMessage2
.
This may be totally clueless question, but I've read about 10 different intros to rxjs and this hasn't quite clicked. I just need to map this scenario to observable pattern and I think I can understand it.
Basically, I want to define an observable function myObs()
that does not "execute immediately" but "executes" whenever the someMethod(message:string,obs:Observable)
is executed. When myObs
is executed, it should do something ansynchronously within it (like get the result of a HTTP request) then set the next value, then fire a complete() so my observer defined in someMethod
can handle the complete and do something with the result.
Edit: I'm not concerned with the timer or native equivalents in rxjs, this is just to simulate any async action, like getting data from the server.