是否有一个操作员,我可以使用“处置”在管道中分配的资源?
假设我有一个可观察的:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 finalize()运算符,该操作员被处置时称为(未订阅)。
由于RXJS 7.3。您还可以使用
tap({finalize:()=> {}})
。也许在您的情况下,您还可以包裹使用
可观察
创建ressurce的逻辑(基本上与有没有办法为rxjs可观测值制造驱动器?):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?):