Combining two observables, skip first value emitted by one observable if it is null

huangapple go评论60阅读模式
英文:

Combining two observables, skip first value emitted by one observable if it is null

问题

I am listening to two observables. In all cases, I want to filter out when obs2 is null.

Now, obs1 can emit a string or a null value. I want to listen to all values of obs1 except the case when its first emitted value is null.

I can probably use a boolean to check if it is obs1's first emitted value, but I was wondering if there is an operator to filter the first value only? Any help would be appreciated.

combineLatest([this.obs1$, this.obs2$]).pipe(
    // TODO: filter out first value of obs if it is null
    filter(([, obs2]) => obs2 != null),
)
.subscribe(([obs1, obs2]) => {
    // do something
});
英文:

I am listening to two observables. In all cases, I want to filter out when obs2 is null.

Now, obs1 can emit a string or a null value. I want to listen to all values of obs1 except the case when its first emitted value is null.

I can probably use a boolean to check if it is obs1's first emitted value, but I was wondering if there is an operator to filter the first value only? Any help would be appreciated.

        combineLatest([this.obs1$, this.obs2$]).pipe(
            // TODO: filter out first value of obs if it is null
            filter(([, obs2]) => obs2!= null),
        )
        .subscribe(([obs1, obs2]) => {
            // do something
        });

答案1

得分: 1

The filter operator提供了第二个参数作为索引,可以用于确定是否是第一个发射值。在您的情况下,听起来您想对obs1$应用一个filter,以防止在其为null时发射第一个值。同样,当obs2$为null时,在combineLatest的结果上也应用一个filter。

类似以下的代码应该有效:

combineLatest([
  this.obs1$.pipe(filter((obs1, i) => i > 0 || !!obs1)), 
  this.obs2$,
]).pipe(
  filter(([, obs2]) => !!obs2)
).subscribe(([obs1, obs2]) => {
  // do something
});
英文:

The filter operator provides the index as the second param, which can be used to determine if its the first emission or not. In your case it sounds like you want to apply a filter to obs1$ to prevent emitting the first emission if it's null. The also, apply a filter on the combineLatest result whenever obs2$ is null.

Something like this should work:

combineLatest([
  this.obs1$.pipe(filter((obs1, i) => i>0 || !!obs1), 
  this.obs2$,
]).pipe(
  filter(([, obs2]) => !!obs2
).subscribe(([obs1, obs2]) => {
  // do something
});

huangapple
  • 本文由 发表于 2023年5月11日 10:49:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76223835.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定