RxJS-如果可观察的输入为空数组,则switchMap不发出值 [英] RxJS - switchMap not emitting value if the input observable is empty array

查看:81
本文介绍了RxJS-如果可观察的输入为空数组,则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.

当用户不喜欢唯一的左侧帖子时,就会出现问题.在这种情况下(当点赞数组变为空时)不会从可观察对象触发任何操作,并且视图也不会更新(总是至少存在一个帖子).

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-如果可观察的输入为空数组,则switchMap不发出值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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