Synchronous and Asynchronous observables

danielpdev

danielpdev

Posted on February 24, 2020

Synchronous and Asynchronous observables

Live example here

Are observables synchronous or asynchronous?

It depends on how they are built.

If you look over RxJS dev docs you'll find this:

Observables are lazy Push collections of multiple values.

I've seen that it's a lot of confusion about this on the internet as a lot of people assume that they are asynchronous because observables are presented as a new way of handling asynchronous code. Let me further explain why I say that it depends by using two examples with a custom rxjs operator:

RxJS operator:
In RxJS an operator is just a function that accepts as
input and observable and further returns a new Observable.

1.Synchronous observable:

const simpleBlockingOperator = (noOfLoops: number) => <T>(source: Observable<T>): Observable<T> =>{
  return new Observable(observable => {
    source.subscribe({
      next: no =>{
        let loops = 0;
        while(loops !== noOfLoops) {
          loops++;
        }
        console.log("Done loooping" + loops, " ", noOfLoops)
        return observable.next(no)
      },
      error: error => observable.error(error),
      complete: () => observable.complete()
    })
  })
};

In the above example we've created an rxjs operator which will loop as many times until we pass noOfLoops. Because our
code is synchronous will result in a blocking operation and trying to click in other parts of the page will not be possible as the main thread is blocked with our process of data.

2.Asynchronous observable:

const simpleNonBlockingOperator = (noOfLoops: number) => <T>(source: Observable<T>): Observable<T> =>{
  return new Observable(observable => {
    source.subscribe({
      next: no =>{
        setTimeout(() => {
          let loops = 0;
          while(loops !== noOfLoops) {
            loops++;
          }
          console.log("Done loooping" + loops, " ", noOfLoops)
          return observable.next(no)
        }, 0);
      },
      error: error => observable.error(error),
      complete: () => observable.complete()
    })
  })
};

In our async operator we've used setTimeout, this setTimeout will assure that the main thread will not get blocked because setTimeout
is a browser API and our code will be moved to the event loop.

More on how JS works

Conclusion

As you have already seen the observables are not by default async and it strongly depends on how they are written.

More tutorials on JS
Follow me on twitter

💖 💪 🙅 🚩
danielpdev
danielpdev

Posted on February 24, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related