使潜在异步的 RxJS observable 确实是异步的

Make potentially asynchronous RxJS observable certainly asynchronous

存在潜在的异步可观察对象,例如:

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

potentiallyButNotNecessarilyAsyncObservable.subscribe(console.log);

它应该是异步可观察的。如果它已经是异步的,最好不要再延迟它,所以我不能做 potentiallyButNotNecessarilyAsyncObservable.delay(0).

如何做到这一点?

您可以使用计划程序控制工作的计划和执行方式。例如,您可以编写 .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>