Are RxJS BehaviorSubjects blocking?

Viewed 44

If my code looks like this:

....a bunch of code in an observable
this.samples.next(null);
...a bunch more code in the method

And this.samples resolves to a BehaviorSubject, does the application wait for all subscribers to be notified and finish their work or does execution continue immediately to the next lines in the current method?

1 Answers

The best way to deal with these questions is to just try it.

Synchronous code:

Write this code and run it:

const subj = new Subject();
subj.subscribe(_ => console.log("Subscr 1"));
subj.subscribe(_ => console.log("Subscr 2"));
console.log("Hello 1");
subj.next(null);
console.log("Hello 2");

The output:

Hello 1
Subscr 1
Subscr 2
Hello 2

The result:

Everything synchronous happens synchronously. There's not any asynchronous code in this example.

Asynchronous code:

Write this code and run it:

const subj = new Subject();
subj.pipe(delay(0)).subscribe(_ => console.log("Subscr 1"));
subj.pipe(delay(0)).subscribe(_ => console.log("Subscr 2"));
console.log("Hello 1");
subj.next(null);
console.log("Hello 2");

The output:

Hello 1
Hello 2
Subscr 1
Subscr 2

The result:

The asynchronous code is run later even though it's waiting 0ms. That's because the current block of synchronous code will complete before anything is taken from JavaScript's event queue.

In Conclusion:

Yes and no? It depends?

Observables allow you to abstract continuation passing through JS's event loop, but it doesn't require you to use it. You can use RxJS to write entirely synchronous code. You'll have to dig into how each operator functions to develop an understanding what what uses the async runtime and what doesn't.

It's all in the documentation :)

Related