【问题标题】:Using RxJs would you unsubscribe when using from(myPromise)?使用 from(myPromise) 时,你会取消订阅 RxJs 吗?
【发布时间】:2020-12-20 23:00:36
【问题描述】:

我在 Angular 中使用 async 管道,或者在组件上使用 takeUntil(...)

export class BaseComponent implements OnDestroy {
  ngUnsubscribe = new Subject<void>();

  ngOnDestroy(): void {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }

}

但是,我一直想知道在使用from(myPromise) 时我需要做什么。 Promise 只提供一个结果,但我已将其转换为 observable,所以感觉就像我制作了一个提供 observable 的等效方法,而不是我应该使用 take(1) 或根据使用情况取消订阅,因为我并不总是直接订阅,而是在 exhaustMap(() =&gt; this.hasTokenExpired$() 中使用它。

  public async hasTokenExpired(): Promise<boolean> {
    const token = await this.getToken();

    if (token) {
      return this.jwtHelper.isTokenExpired(token);
    }

    return true;
  }

  // Observable equivalent method:
  public hasTokenExpired$(): Observable<boolean> {
    return from(this.hasTokenExpired()); // Could pipe `take(1)` permanently
  }

我应该在from(myPromise) 上使用take(1) 吗?一段时间以来,我一直在想,以防这会导致内存泄漏,但我找不到确认我应该这样做的文章。

此外,如果有更好的方法来制作这些可观察到的等效方法,我总是愿意接受建议。

【问题讨论】:

标签: angular rxjs rxjs6


【解决方案1】:

在这种情况下,您永远不需要使用take,因为从 Promise 创建的 Observable 只会:

  • 如果 Promise 解决,则发出 1 个值并完成。
  • Promise 拒绝时出错。

这个答案也可能有助于阅读:Does toPromise() unsubscribe from the Observable?

【讨论】:

  • 感谢您的确认,特别感谢您的链接
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-24
  • 1970-01-01
  • 2017-03-26
  • 2020-10-28
  • 2020-02-14
  • 2021-11-18
相关资源
最近更新 更多