【问题标题】:rxjs can manual subscription handling be replaced with switchmaprxjs 可以用 switchmap 代替手动订阅处理
【发布时间】:2019-02-27 15:25:55
【问题描述】:

我有一项服务来管理登录用户。我有第二个服务,它为登录用户的列表项提供数据源。这两种服务都是单例的,并且(可能)比一个用户登录的寿命更长。

这种模式经常出现:

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(...)

另外,我应该在 else 中返回什么?在这种情况下,我根本不需要订阅工作,那么仅返回 null 或 undefined 是否安全?或者我应该返回空的 Observable (import { EMPTY } from 'rxjs')? (如果没有活跃用户,订阅中的代码不需要运行。)

【问题讨论】:

  • 是的,您可以只返回empty()switchMap 将自动取消订阅任何内部 Observable。如果你想确定你可以使用finalize(),比如.getUserSpecificObservable(loggedInUser).pipe(finalize(() => console.log('unsubed')))

标签: rxjs rxjs6


【解决方案1】:

只要你对未定义的值不感兴趣,你可以在调用第二个服务之前将它们过滤掉:

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

您还可以在此处查看主要想法:https://stackblitz.com/edit/typescript-p75oku

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2021-10-25
    • 1970-01-01
    相关资源
    最近更新 更多