是否有一个操作员,我可以使用“处置”在管道中分配的资源?

发布于 2025-02-01 10:41:33 字数 739 浏览 3 评论 0原文

假设我有一个可观察的:

declare function allocateLeakyThing(input: string): { dispose: () => void; };

const somethingLeaky$ = input$.pipe(
  map(allocateLeakyThing)
);

AllocateLeakyThing()返回必须通过调用其Dispose()方法来手动处理的资源,以防止内存泄漏。如果输入$排放新值,则我应该处置先前分配的资源;如果可观察到的可观察到的订阅,则如果分配给它,它也应该处理资源。

出于第一个目的,我可以写:

const somethingLeaky$ = input$.pipe(
  withLatestFrom(somethingLeaky$.pipe(startsWith(undefined))),
  tap(([input, somethingLeaky]) => somethingLeaky?.dispose()),
  map(([input])=>allocateLeakyThing(input))
);

第二个目的呢?有没有办法与可观察到的可观察到这一点(例如不涉及使用另一个主题)?

Say I have an observable:

declare function allocateLeakyThing(input: string): { dispose: () => void; };

const somethingLeaky$ = input$.pipe(
  map(allocateLeakyThing)
);

where allocateLeakyThing() returns a resource that has to be manually disposed by calling its dispose() method in order to prevent memory leak. If input$ emits a new value, I should dispose the previously allocated resource; if this observable is unsubscribed, it should dispose the resource too, if it's ever allocated.

For the first purpose I can write:

const somethingLeaky$ = input$.pipe(
  withLatestFrom(somethingLeaky$.pipe(startsWith(undefined))),
  tap(([input, somethingLeaky]) => somethingLeaky?.dispose()),
  map(([input])=>allocateLeakyThing(input))
);

What about the second purpose? Is there a way to do this inline with this observable (e.g. does not involve using another subject)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

何以畏孤独 2025-02-08 10:41:33

您可以使用 finalize()运算符,该操作员被处置时称为(未订阅)。

由于RXJS 7.3。您还可以使用tap({finalize:()=> {}})

也许在您的情况下,您还可以包裹使用可观察创建ressurce的逻辑(基本上与有没有办法为rxjs可观测值制造驱动器?):

new Observable(observer => {
  // create resource
  // ...

  // Return teardown function that will be called when the Observable is unsubscribed.
  return () => resource.close();
});

You can use finalize() operator that is called when a chain is being disposed (unsubscribed).

Since RxJS 7.3. you can also use tap({ finalize: () => {} }).

Maybe in your situation you could also wrap the logic that creates the ressurce with Observable (basically the same thing as in Is there a way to make a destructor for RXJS Observables?):

new Observable(observer => {
  // create resource
  // ...

  // Return teardown function that will be called when the Observable is unsubscribed.
  return () => resource.close();
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文