Aquarius_Girl
Aquarius_Girl

Reputation: 22946

What is the way to make Observables behave in both - synchronous and asynchronous ways?

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?

Upvotes: 4

Views: 171

Answers (1)

codeandcloud
codeandcloud

Reputation: 55248

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>

Upvotes: 6

Related Questions