rxjs可以将手动订阅处理替换为switchmap

时间:2018-09-24 06:40:59

标签: rxjs rxjs6

我有一项服务可以管理登录用户。我还有第二项服务,它为登录用户的列表项提供数据源。两种服务都是单例的,并且生存期可能超过一个用户登录的时间。

我经常重复这种模式:

this._loggedInUserService.loggedInUserObservable.subscribe(loggedInUser: User => {

  // Remove old subscription
  if (this._subscription) {
    this._subscription.unsubscribe()
    this._subscription = null
  }

  if (loggedInUser) {
    this._subscription = this._otherService.getUserSpecificObservable(loggedInUser).subscribe(...)
  }

})

现在我已经阅读了有关switchMap的内容,以下内容在功能上是否与上面的代码相同?如果用户更改,订阅是否正确结束?

this._loggedInUserService.loggedInUserObservable.pipe(
  switchMap(user => {
    if (user) {
      return this._otherService.getUserSpecificObservable(loggedInUser)
    } else {
      // What to return here?
    }
  })
).subscribe(...)

另外,我应该在其他地方返回什么?在那种情况下,我根本不需要订阅就可以工作,所以仅返回null或undefined是否安全?还是应该返回空的Observable(从'rxjs'导入{EMPTY})? (如果没有活动用户,则无需运行订阅中的代码。)

1 个答案:

答案 0 :(得分:0)

只要您对未定义的值不感兴趣,就可以在调用第二项服务之前将其过滤掉:

this._loggedInUserService.loggedInUserObservable.pipe(
  filter(user => !!user),
  switchMap(user => this._otherService.getUserSpecificObservable(user))
).subscribe(...)

您还可以在这里查看基本思想:https://stackblitz.com/edit/typescript-p75oku