【发布时间】: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')))