I have code like this:
get dislpayHello(): boolean {
let result = false;
console.log('start');
let observable = of(true);
observable.subscribe((display) => {
console.log('set value');
result = true;
});
console.log('finish');
return result;
}
I always thought that, whatever callback we put in subscribe(), it will be executed asynchronously, and since JavaScript is one threaded, callback will be executed after whatever’s left in current block of code. So in this example, I would expect dislpayHello
method to always return false
, and console to log in order: ‘start’, ‘finish’, ‘setValue’. However this is not what happens, when I tried it, subscribe block executes before rest of code. Was I simply wrong all this time?
How do I know whether subscription will be executed immediately, or it will be postponed? Is there any documentation or articles I could read on that?
2
Answers
It is a misconception that Observables are always asynchronous, usually because they are often used to handle things like HTTP requests which are:
https://rxjs.dev/guide/observable
I recommend reading https://rxjs.dev/guide/observable, which clarifies this. Excerpts:
(where
foo
was defined as):Furthermore:
Basically,
subscribe
can be sync or async, depending on how you are using it. If itsnext
is evaluated synchronously, then it is sync. Otherwise, it’s async.