RxJS - 如果输入 observable 是空数组,switchMap 不会发出值

Dan*_*nov 5 rxjs firebase angularfire2 angular2-observables angular

我有一个设置,我可以在 firebase 中查询用户最喜欢的帖子列表。

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

当用户不喜欢唯一留下的帖子时,就会出现问题。在这种情况下(当 likes 数组变空时)不会从 observable 中触发任何内容并且视图不会更新(总是至少有一个帖子存在)。

一方面,这种行为似乎合乎逻辑且可以理解,但另一方面,即使 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$;
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*nov 5

通过在 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$;
}
Run Code Online (Sandbox Code Playgroud)