使潜在的异步RxJS observable肯定是异步的

时间:2017-09-06 01:50:30

标签: javascript rxjs rxjs5

可能存在异步的可观察性,例如:

const potentiallyButNotNecessarilyAsyncObservable = [
  Observable.of('sync'),
  Observable.of('async').delay(100)
][Math.round(Math.random())];

potentiallyButNotNecessarilyAsyncObservable.subscribe(console.log);

它应该是异步可观察的。如果它已经是异步的,那么我们不希望进一步延迟它,所以我不能potentiallyButNotNecessarilyAsyncObservable.delay(0)

如何做到这一点?

1 个答案:

答案 0 :(得分:3)

您可以使用调度程序控制工作的安排和执行方式。例如,您可以编写.observeOn(Rx.Scheduler.async)并使用setTimeoutsetInterval来安排工作,而不是同步递归调用。这是一个高级主题,如果您想更好地了解它,我建议您阅读this great documentation on Schedulers

以下是两个例子,第一个是在一个刻度中执行,第二个是在几个中执行:

const { of, asapScheduler } = rxjs; // = require("rxjs")
const { observeOn } = rxjs.operators; // = require("rxjs/operators")

const sync$ = of('sync');

// by default RxJS will pick a default scheduler by using the principle of least concurrency
// in this case it is a null or undefined Schedulr which means notifications are delivered synchronously and recursively
console.log('--------- default(null) Scheduler ---------------');
console.log('just before subscribe');
sync$.subscribe({
  next: x => console.log('got value ' + x),
  error: err => console.error('something wrong occurred: ' + err),
  complete: () => console.log('done'),
});
console.log('just after subscribe');


const async$ = sync$.pipe(
  observeOn(asapScheduler)
);

// "got value sync" is printed after "just after subscribe"
console.log('--------- Rx.Scheduler.async Scheduler ----------');
console.log('just before subscribe');
async$.subscribe({
  next: x => console.log('got value ' + x),
  error: err => console.error('something wrong occurred: ' + err),
  complete: () => console.log('done'),
});
console.log('just after subscribe');
<script src="https://unpkg.com/rxjs@6.2.2/bundles/rxjs.umd.min.js"></script>