代码之家  ›  专栏  ›  技术社区  ›  Aquarius_Girl

什么样的方法可以使可观察对象同时以同步和异步的方式工作?

  •  3
  • Aquarius_Girl  · 技术社区  · 5 年前

    发件人: What is the difference between Promises and Observables?

    这意味着我们可以用一种特殊的方式编写代码,这种方式可以使可观察对象有时以同步方式工作,有时以异步方式工作。

    可观察对象的默认行为是什么?它是同步的还是异步的?

    1 回复  |  直到 5 年前
        1
  •  6
  •   codeandcloud    5 年前

    1. 如果基础调用是synchoronous,则observable将表现为synchoronous。

    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$');
    <script src="//cdnjs.cloudflare.com/ajax/libs/rxjs/6.6.3/rxjs.umd.min.js">
    </script>

    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$');
    <script src=“//cdnjs.cloudflare.com/ajax/libs/rxjs/6.6.3/rxjs.umd.min.js”>
    </脚本>