RxJS - 如果输入可观察对象为空数组,则 switchMap 不会发出值

RxJS - switchMap not emitting value if the input observable is empty array

我有一个设置,我可以在其中查询 firebase 以获取用户收藏夹 post 的列表。

基本上,首先我查询用户喜欢,然后为每个喜欢获得相应的 post - 所有在一个可观察的序列中。

当用户不喜欢唯一剩下的 post 时,问题就出现了。在那种情况下(当 likes 数组变为空时)不会从 observable 中触发任何东西并且视图不会更新(总是至少存在一个 post)。

一方面,这种行为似乎合乎逻辑且可以理解,但另一方面,即使 switchMap 的输入为空,我也不确定如何让最终的 Observable 发出。也许应该改变运营商。

getUserFavourites(userId = ""):Observable<Post[]>
{
  if (!this.userFavourites$) {
    this.userFavourites$ = this.af.database.list('/ranks_by_user/' + userId, {
        query: {
          limitToFirst: 50
        }
      }) //Emits value here (even empty array)
      .switchMap((likes: any[]) => Observable.combineLatest(
        likes.map(like => this.af.database.object("/posts/" + like.$key).first())
      )) //Does not emit new value here if likes array was empty
      .map(p => {
        return p.map(cit => Post.unpack(p));
      }).publishReplay(1).refCount()
  }
  return this.userFavourites$;
}

通过在 switchMap 中添加条件解决了问题:

原创 - https://github.com/ReactiveX/rxjs/issues/1910

getUserFavourites(userId = ""):Observable<Post[]>
{
  if (!this.userFavourites$) {
    this.userFavourites$ = this.af.database.list('/ranks_by_user/' + userId, {
        query: {
          limitToFirst: 50
        }
      }) //Emits value here (even empty array)
      .switchMap((likes: any[]) => {
      return likes.length === 0 ?
        Observable.of(likes) :
        Observable.combineLatest(
          likes.map(like => this.af.database.object("/citations/" + like.$key))
      )
    }) //Emits either combined observables array or empty array
      .map(p => {
        return p.map(cit => Post.unpack(p));
      }).publishReplay(1).refCount()
  }
  return this.userFavourites$;
}
.switchMap((likes) => likes.length > 0 ?
   Observable.combineLatest(
    likes.map(like => this.af.database.object("/posts/" + like.$key).first():
   Observable.empty() // if emit empty() then .map() will not run 
 )
 .map(...)