angular - RxJs - 当观察到的值为假时取消订阅,同时期待副作用
问题描述
我有一种情况,当我们通过 SSE 从 BE 接收更新时可以打开一个对话框,但当另一个更新更改以前的状态时关闭。
我创建了一个辅助函数,它从一个内部调用effect
并将打开的对话框引用作为参数。在那里我订阅了设备状态更新,如果满足条件,对话框关闭并且选择器应该被取消订阅。但是当用户手动关闭对话框时也应该取消订阅。现在生成的代码对我来说似乎很奇怪。
private closeOnStatusChange(dialog: MatDialogRef<ConfirmDialogComponent>): void {
this.store
.select(fromDevice.selectDeviceStatus)
.pipe(
map(({ deviceStatus }) => deviceStatus === DeviceStatus.INACTIVE || deviceStatus === DeviceStatus.FAILED),
takeWhile(shouldClose => !shouldClose), // if status is 'ok', observe but do not unsubscribe
takeUntil(dialog.afterClosed()), // unsubscribe when dialog is closed
filter(shouldClose => shouldClose), // status is 'fail', continue and close the dialog
tap(() => dialog.close())
)
.subscribe();
}
老实说,我无法弄清楚这个链条是正确的还是有一些隐藏的陷阱。经过简短的测试后,它看起来可以正常工作,但感觉不对。知道如何处理这个问题,可能不使用辅助变量吗?
解决方案
尝试使用take
- 它只需要 1 个事件并立即取消订阅。我还把你tap
转为订阅(但你可以在之后离开take(1)
)。头部代码 - 未经测试
.pipe(
map(({ deviceStatus }) => deviceStatus === DeviceStatus.INACTIVE || deviceStatus === DeviceStatus.FAILED),
takeWhile(shouldClose => !shouldClose), // if status is 'ok', observe but do not unsubscribe
takeUntil(dialog.afterClosed()), // unsubscribe when dialog is closed
filter(shouldClose => shouldClose), // status is 'fail', continue and close the dialog
take(1)
)
.subscribe(() => dialog.close())
推荐阅读
- amazon-web-services - 通过 redshift-data API 从 S3 参数化 Redshift COPY
- python - 如何在 Python 中用 BeautifulSoup 理解“递归”
- vue.js - 在使用 rollup.js 的 VS Code 扩展应用程序中,我缺少哪些配置设置和/或逻辑以实现 Vue 兼容性?
- configuration - 如何将链接器命令行选项添加到介子中
- javascript - 在 React 中使用 immutability-helper,一次更新多个值
- c++ - 如何打印出包含关键字的 CSV 文件的整行?
- c# - 根据条件显示主页
- https - 最近的网络设备浏览器支持 WebAssembly/SharedArrayBuffer?
- java - 如何从 json JAVA SPRING 获取特定数据?
- numpy - 如何在模型构建期间将 kerastensor 转换为 numpy 数组,反之亦然