创建一次性订阅 [英] Create one-time subscription
本文介绍了创建一次性订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要创建对 Observable
的订阅,该订阅在第一次调用时立即处理.
I need to create a subscription to an Observable
that is immediately disposed of when it is first called.
有没有类似的东西:
observable.subscribeOnce(func);
我的用例,我在快速路由处理程序中创建订阅,并且每个请求都会多次调用订阅.
My use case, I am creating a subscription in an express route handler and the subscription is being called multiple times per request.
推荐答案
不能 100% 确定您需要什么,但如果您只想观察第一个值,则使用 first()
或 take(1)
:
Not 100% certain about what you need, but if you only want to observe the first value, then use either first()
or take(1)
:
observable.first().subscribe(func);
注意:.take(1)
和 .first()
都在满足条件时自动退订
note: .take(1)
and .first()
both unsubscribe automatically when their condition is met
来自编码员的评论.
import { first } from 'rxjs/operators'
observable
.pipe(first())
.subscribe(func);
这篇关于创建一次性订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文