在RxJS中是否有类似”tap”的操作,可以忽略通知类型?

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

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&lt;T&gt;(fn: () =&gt; void): MonoTypeOperatorFunction&lt;T&gt; {
  return tap({
    next: _ =&gt; fn(),
    error: _ =&gt; fn(),
    complete: fn
  });
}

Now you can use it like this:

something.pipe(
    anyTap(() =&gt; this.isLoading = false),
)

答案2

得分: 2

something.pipe(
  finalize(() => {
    this.isLoading = false;
  });
)
英文:
something.pipe(
  finalize(() =&gt; {
    this.isLoading = false;
  });
)

huangapple
  • 本文由 发表于 2023年3月3日 21:18:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75627586.html
匿名

发表评论

匿名网友

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

确定