Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS What difference with Scheduler.queue and null?

Tags:

rxjs

rxjs5

enter image description here

Example:

ob$.subscribeOn(Scheduler.queue) 
 .subscribe(() => {...})

or

ob$.subscribe(() => {...})

There is nothing difference, right?

like image 352
quanwei li Avatar asked Jun 11 '26 10:06

quanwei li


1 Answers

The difference is apparent when you look at how the queue scheduler affects the behaviour of combineLatest.

Compare the behaviour of this snippet in which no scheduler (i.e. the null scheduler) is specified:

const a = Rx.Observable.of(1, 2);
const b = Rx.Observable.of(3, 4);
const c = Rx.Observable.of(5, 6);

console.log("before");
Rx.Observable
  .combineLatest(a, b, c)
  .subscribe(value => console.log(JSON.stringify(value)));
console.log("after");
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://unpkg.com/rxjs@5/bundles/Rx.min.js"></script>

With this snippet:

const a = Rx.Observable.of(1, 2, Rx.Scheduler.queue);
const b = Rx.Observable.of(3, 4, Rx.Scheduler.queue);
const c = Rx.Observable.of(5, 6, Rx.Scheduler.queue);

console.log("before");
Rx.Observable
  .combineLatest(a, b, c, Rx.Scheduler.queue)
  .subscribe(value => console.log(JSON.stringify(value)));
console.log("after");
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://unpkg.com/rxjs@5/bundles/Rx.min.js"></script>

Note that both snippets run synchronously. The queue scheduler executes scheduled actions synchronously when no delay is specified.

In the first snippet, the observables are enumerated in a depth-first manner. That is, all of the values from the source observable a are enumerated before the values from the observables b and c are enumerated. That sees only two combined values emitted with the last values from a and b and both values from c.

However, in the second snippet the values are enumerated in a breadth-first manner. That is, a value is enumerated from a followed by a value from b, etc. That sees more combinations emitted.

In short, the queue scheduler behaves this way because when an action is scheduled whilst an already-scheduled action is being executed, the newly scheduled action is queued.

like image 71
cartant Avatar answered Jun 17 '26 23:06

cartant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!