英文:
Is there something like tap in RxJS that ignores notification type?
问题
通常,tap
管道用于副作用,比如日志记录。在我的情况下,我只想将 isLoading
属性设置为 false
。关键是这个地方不应关心是下一个通知还是错误类型的通知,但是 tap
仍然需要区分它们才能工作,所以我需要有重复的代码:
something.pipe(
tap({
next: () => {
this.isLoading = false;
},
error: () => {
this.isLoading = false;
}
}),
)
是否有任何管道,或者一些配置 tap
的方法,以便我只提供一个回调函数,无论通知类型如何,都会运行?例如:
something.pipe(
anyTap(() => {
this.isLoading = false;
}),
)
无论 something
返回什么,anyTap
都会运行其回调函数。
英文:
In general tap
pipe is for side-effects such as logging. In my case I just want to set isLoading
property to false
. The key is this place shouldn't care whether it's next or error type of notification but still tap needs to have it distinguished to work so I need to have duplicated code:
something.pipe(
tap({
next: () => {
this.isLoading = false;
},
error: () => {
this.isLoading = false;
}
}),
)
Is there any pipe, or some way to configure tap so I just provide one callback function which would run no matter what the notification type is? Eg.
something.pipe(
anyTap(() => {
this.isLoading = false;
}),
)
And whatever something
returns, anyTap
would run it's callback function anyway.
答案1
得分: 2
以下是已翻译的内容:
这是您可能如何定义 anyType 操作符:
function anyTap<T>(fn: () => void): MonoTypeOperatorFunction<T> {
return tap({
next: _ => fn(),
error: _ => fn(),
complete: fn
});
}
现在您可以这样使用它:
something.pipe(
anyTap(() => this.isLoading = false),
)
英文:
Here's how you might define the anyType operator:
function anyTap<T>(fn: () => void): MonoTypeOperatorFunction<T> {
return tap({
next: _ => fn(),
error: _ => fn(),
complete: fn
});
}
Now you can use it like this:
something.pipe(
anyTap(() => this.isLoading = false),
)
答案2
得分: 2
something.pipe(
finalize(() => {
this.isLoading = false;
});
)
英文:
something.pipe(
finalize(() => {
this.isLoading = false;
});
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论