英文:
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
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论