RxJS - 如果输入 observable 是空数组,switchMap 不会发出值 [英] RxJS - switchMap not emitting value if the input observable is empty array

查看:24
本文介绍了RxJS - 如果输入 observable 是空数组,switchMap 不会发出值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the setup where I query firebase for list of user favourite posts.

基本上,首先我查询用户喜欢,然后为每个喜欢获取相应的帖子 - 全部在一个可观察的序列中.

Basically, at first I query for user likes and then for each like get the corresponding post - all in one observable sequence.

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

The problem arises when user dislikes the only left post. In that case (when the likes array becomes empty) nothing is fired from the observable and view is not updated (there is always at least one post present).

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

On the one hand, this behaviour seems logical and understandable, but on the other hand, I'm not sure how to make final Observable emit even if the input to the switchMap was empty. Maybe should change the operator.

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中添加条件解决了问题:

Solved the problem by adding a condition inside 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$;
}

这篇关于RxJS - 如果输入 observable 是空数组,switchMap 不会发出值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆