Sync and Async Observables

Sync and Async Observables

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 the number passed is reached. Because our code is synchronous will result in blocking the main thread and trying to click in other parts will not be possible.

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.

Live example here

Share This: