4

From: What is the difference between Promises and Observables?

a Promise is always asynchronous, while an Observable can be either synchronous or asynchronous

This means we can write the code in a particular way which can make Observables behave in a synchronous way sometimes and asynchronous ways othertimes.

What is the default behaviour of an Observable? Is it synchronous or asynchronous?

What would be the way to write such functionality that sometimes the Observables behave asynchronous and sometimes synchronous?

Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411

1 Answers1

6

It really depends on the how the Observable gets called.

  1. If the underlying call is synchoronous, observable will behave synchoronous.

const { Observable } = rxjs;

const helloWorld$ = new Observable(observer => {
  observer.next('Hello World');
  observer.complete();
});

console.log('Before subscribing helloWorld$');

helloWorld$.subscribe({
  next: console.log,
  complete: () => console.log('helloWorld$ on complete')
});

console.log('After subscribing helloWorld$');
<script src="//cdnjs.cloudflare.com/ajax/libs/rxjs/6.6.3/rxjs.umd.min.js">
</script>
  1. If the underlying call is asynchoronous, observable will behave asynchoronous.

const { Observable } = rxjs;

const helloEarth$ = new Observable(observer => {
  // mocking an ajax call
  setTimeout(() => {
    observer.next('Hello Earth from a galaxy far, far away...');
    observer.complete();
  }, 1000);
});

console.log('Before subscribing helloEarth$');

helloEarth$.subscribe({
  next: console.log,
  complete: () => console.log('helloEarth$ on complete')
});

console.log('After subscribing helloEarth$');
<script src="//cdnjs.cloudflare.com/ajax/libs/rxjs/6.6.3/rxjs.umd.min.js">
</script>
naveen
  • 53,448
  • 46
  • 161
  • 251
  • Kindly explain your code. Which part is synchronous and which is asynchronous? Please write comments in code. – Aquarius_Girl Oct 04 '20 at 07:53
  • @Aquarius_Girl: The console.log explains the code flow, if you take a look at it. Please let me know whether you need elaboration anywhere specifically – naveen Oct 05 '20 at 07:51