首页 > 解决方案 > 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();
}

老实说,我无法弄清楚这个链条是正确的还是有一些隐藏的陷阱。经过简短的测试后,它看起来可以正常工作,但感觉不对。知道如何处理这个问题,可能不使用辅助变量吗?

标签: angulartypescriptrxjsngrx

解决方案


尝试使用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())

推荐阅读