kun
kun

Reputation: 4237

When is rxjs observable subscribe executed synchronously?

With below code block,

let ob = of(1,2,3);
ob.subscribe((v)=>{
   console.log(v)
})
console.log("end")

the values are emitted synchronously. Is the function within subscribe guaranteed to be executed before print end? so the output will always be.

1
2
3
end

Upvotes: 5

Views: 2600

Answers (3)

Adrian Brand
Adrian Brand

Reputation: 21638

Not if the observable emits later

const { BehaviorSubject } = rxjs;

let bs$ = new BehaviorSubject(1);

setTimeout(() => { bs$.next(2); }, 500);
setTimeout(() => { bs$.next(3); }, 1000);

bs$.subscribe(v => {
   console.log(v)
});

console.log('end');
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.3/rxjs.umd.min.js"></script>

Upvotes: 1

Manuel Panizzo
Manuel Panizzo

Reputation: 896

The observables are Stream of Data notasync functions. runs synchronously and depends of the logic inside the osbervable it call the next method synchroniusly oner or manytimes (like a of operator) or async like if you call the next method inside of SetTimeout function.

Upvotes: 0

Fan Cheung
Fan Cheung

Reputation: 11345

if your observable stream is running sync code only, yes it just like running normal function execution synchronously, but if it's async it'll run asynchronously, whereas promise will always run asynchronously

The async version of your code will be something like

let ob = of(1,2,3).pipe(mergeMap(num=>timer(0),_=>num);
ob.subscribe((v)=>{
   console.log(v)
})
console.log("end")

Upvotes: 3

Related Questions