让 Observables 以同步和异步方式运行的方法是什么?

Aqu*_*irl 3 javascript asynchronous rxjs typescript angular

来自:Promises 和 Observables 有什么区别?

Promise 总是异步的,而 Observable 可以是同步的也可以是异步的

这意味着我们可以以特定的方式编写代码,这可以使 Observable 有时以同步方式运行,有时以异步方式运行。

Observable 的默认行为是什么?它是同步的还是异步的?

编写这种有时 Observable 表现异步有时同步的功能的方法是什么?

nav*_*een 6

这实际上取决于 Observable 的调用方式。

  1. 如果底层调用是同步的,observable 将表现同步。

const { Observable } = rxjs;

const helloWorld$ = new Observable(observer => {
  observer.next('Hello World');
  observer.complete();
});

console.log('Before subscribing helloWorld$');

helloWorld$.subscribe({
  next: console.log,
  complete: () => console.log('helloWorld$ on complete')
});

console.log('After subscribing helloWorld$');
Run Code Online (Sandbox Code Playgroud)
<script src="//cdnjs.cloudflare.com/ajax/libs/rxjs/6.6.3/rxjs.umd.min.js">
</script>
Run Code Online (Sandbox Code Playgroud)

  1. 如果底层调用是异步的,则 observable 的行为将是异步的。

const { Observable } = rxjs;

const helloEarth$ = new Observable(observer => {
  // mocking an ajax call
  setTimeout(() => {
    observer.next('Hello Earth from a galaxy far, far away...');
    observer.complete();
  }, 1000);
});

console.log('Before subscribing helloEarth$');

helloEarth$.subscribe({
  next: console.log,
  complete: () => console.log('helloEarth$ on complete')
});

console.log('After subscribing helloEarth$');
Run Code Online (Sandbox Code Playgroud)
<script src="//cdnjs.cloudflare.com/ajax/libs/rxjs/6.6.3/rxjs.umd.min.js">
</script>
Run Code Online (Sandbox Code Playgroud)