angular - RxJs - 如何使用 takeuntil 运算符返回通知值
问题描述
我有一个简单的 Rxjs 计时器,它会一直运行直到通知器发出一些东西,直到这里非常基本。
enum TimerResult = {
COMPLETE,
ABORTED,
SKIPPED
};
_notifier: Subject<TimerResult> = new Subject();
notifier$: Observable<TimerResult> = this._notifier.asObservable();
simpleTimer$ = interval(1000);
startTimer(): Observable<number> <-- **here I want a timerResult** {
return simpleTimer$.pipe(
tap(()=>doSomethingBeautifulWhileRunning),
takeUntil(this.notifier$)
)
}
我想要实现的是获得通知程序发出的值作为结果。
我不需要中间值,我只需要知道它何时完成以及结果如何。
simpleTimer$.pipe(
tap(()=>doSomethingBeautifulWhileRunning),
last(),
takeUntil(this.notifier$)
).subscribe((result)=>{
// Here, of course, I get the last value
// I need instead the value coming from notifier$
});
我用 Rx 操作符尝试了很多可能的解决方案,但没有一个能按预期工作。我发现唯一能产生可接受的结果(但恕我直言非常非常肮脏)的是:
startTimer(): Observable<TimerResult>{
simpleTimer$.pipe(...).subscribe(); <-- fire the timer, automatically unsubscribed by takeUntil
return this.notifier$.pipe(first());
}
获得这个的最佳“Rx”方式是什么?我希望我已经足够清楚了,任何帮助都非常感谢:)
解决方案
您可以merge
使用原始流通知通知器并从那里获取结果,请尝试以下示例。
const notifier = timer(5000).pipe(mapTo("done"));
merge(interval(1000)
.pipe(takeUntil(notifier)),
notifier
)
.subscribe(console.log,null,
_=>console.log('complete')
);
推荐阅读
- swift - 如何使用 SwiftUI 中的 documentID 删除特定的 Cloud Firestore 文档?
- python - 如何将拉普拉斯算子应用于文件夹中的每个图像
- excel - Excel:如何找到某一行并将该行中的值乘以某个数字?
- python - TemplateSyntaxError: 意外的 '%'
- react-native - React Native Button onPressIn 动画请求
- r - 部分包加载失败
- c++ - 如何监控 TLB 未命中(windows)?
- java - Hibernate 和 EJB:如何正确使用 @TransactionAttribute(value = TransactionAttributeType.REQUIRES_NEW)?
- python - 如何将文本文件中的多值字典作为字典导入 python 以及可能出现的问题。需要回答
- reactjs - 使用 React State Hook,设置多个状态后调用函数