简体   繁体   English

Observable 中的 Async/Await

[英]Async/Await inside the Observable

How can I use async/await inside the Observable??如何在 Observable 中使用 async/await? With this code I'm unable to trigger the unsubscribe function within observable thus interval is not cleared.使用此代码,我无法在 observable 内触发取消订阅功能,因此不会清除间隔。

const { Observable } = require("rxjs");

const test = () => new Observable(async (subscriber) => {
  await Promise.resolve();

  const a = setInterval(() => {
    subscriber.next(Math.random());
    console.log("zz");
  }, 500);

  return () => {
    console.log("asdsad");
    clearInterval(a);
  };
});

const xyz = test().subscribe(console.log);


setTimeout(() => {
  xyz.unsubscribe();
}, 3000);

Async/Await inside an observable is not supported.不支持 observable 内的 Async/Await。 However, it can be done with a behavior subject and an asynchronous nested function.但是,它可以通过行为主体和异步嵌套函数来完成。

Create a behavior subject, convert it to an observable ( .asObservable() ), execute the asynchronous nested function, return the observable.创建一个行为主体,将其转换为可观察对象( .asObservable() ),执行异步嵌套函数,返回可观察对象。 Here's an example.这是一个例子。

function getProgress() {

    // Change this value with latest details
    const value = new BehaviorSubject('10%');
    const observable = value.asObservable();

    // Create an async function
    const observer = async() => {
      // Perform all tasks in here
      const wait1 = await new Promise(resolve => setTimeout(resolve, 3000));
      value.next('66%');

      const wait2 = await new Promise(resolve => setTimeout(resolve, 3000));
      value.next('100%');

      // Complete observable
      value.complete();
    }

    // Call async function & return observable
    observer();
    return observable;
  }

It's very readable and works like a charm.它非常易读,就像一个魅力。

First of all, subscriber passed to observable contructor cannot be async function. 首先,传递给可观察构造器的订户不能是异步功能。 There is no support for that. 没有对此的支持。

If you need to create observable from promise, use from : 如果您需要从promise创建可观察的对象,请使用from

import { from } from 'rxjs';
const observable = from(promise);

But considering your scenario. 但是考虑您的情况。

Because there is no way to cancel native js promise, you cannot realy unsubscribe from such created observable, so: 由于无法取消本机js承诺,因此您无法真正取消订阅此类创建的Observable,因此:

const obs = from(new Promise(resolve => {
  setTimeout(() => {
    console.log('gonna resolve');
    resolve('foo');
  }, 1000);
}));

const sub = obs.subscribe(console.log);
setTimeout(() => sub.unsubscribe(), 500);

will print: 将打印:

gonna resolve
gonna resolve
gonna resolve
(...)

so yeah: gonna resolve will be printed in the cosole all the time, but nothing more - result passed to resolve will be ignored - just not logged. 所以,是的: gonna resolve将一直打印在控制台上,但仅此而已-传递给解析的结果将被忽略 -只是不记录。

From the other hand, if you remove that unsubscribtion ( setTimeout(() => sub.unsubscribe(), 500); ) this time you will see: 另一方面,如果您这次取消取消订阅( setTimeout(() => sub.unsubscribe(), 500); ),则您将看到:

gonna resolve
foo
gonna resolve
gonna resolve
gonna resolve
(...)

There is one way that maybe will help you - defer - but it's not strictly related with your question. 有一种可能会帮助您的方法- defer -但这与您的问题并不严格相关。

import { defer } from 'rxjs';

defer(async () => {
  const a = await Promise.resolve(1);
  const b = a + await Promise.resolve(2);

  return a + b + await Promise.resolve(3);
}).subscribe(x => console.log(x)) // logs 7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM