RXJS条件操作员简化

发布于 2025-02-04 16:35:14 字数 803 浏览 3 评论 0 原文

我有此工作代码:

import { timer, take, pipe, map, mergeMap, iif, of } from 'rxjs'

const double = () => {
  return pipe(
    map((x: number) => x * 2)
  )
} 

const triple = () => {
  return pipe(
    map((x: number) => x * 3)
  )
}

timer(0, 1000).pipe(
  take(4),
  mergeMap(x => iif(() => x <= 1, of(x).pipe(double()), of(x).pipe(triple())))
).subscribe(x => {
  console.log('output', x)
})

这是工作stackblitz

按预期的输出是:

output 0
output 2
output 6
output 9

只有一个问题。这条线很冗长:

mergeMap(x => iif(() => x <= 1, of(x).pipe(double()), of(x).pipe(triple())))

可以简化这条线吗?

I have this working code:

import { timer, take, pipe, map, mergeMap, iif, of } from 'rxjs'

const double = () => {
  return pipe(
    map((x: number) => x * 2)
  )
} 

const triple = () => {
  return pipe(
    map((x: number) => x * 3)
  )
}

timer(0, 1000).pipe(
  take(4),
  mergeMap(x => iif(() => x <= 1, of(x).pipe(double()), of(x).pipe(triple())))
).subscribe(x => {
  console.log('output', x)
})

Here is a working Stackblitz.

Output as expected is:

output 0
output 2
output 6
output 9

Only one question. This line is pretty verbose:

mergeMap(x => iif(() => x <= 1, of(x).pipe(double()), of(x).pipe(triple())))

Is it possible to simplify this line?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

凉宸 2025-02-11 16:35:14

与其进行 double triple 自定义操作员,您可以简单地使其功能,只需使用 map

const double = (x: number) => x * 2;
const triple = (x: number) => x * 3;

timer(0, 1000).pipe(
  take(4),
  map(x => (x <= 1 ? double(x) : triple(x)))
);

如果修改来自可观察的源,您可以使用 Mergemap

const double$ = (x: number) => of(x * 2);
const triple$ = (x: number) => of(x * 3);

timer(0, 1000).pipe(
  take(4),
  mergeMap(x => x <= 1 ? double$(x) : triple$(x))
);

stackblitz

Instead of making double and triple custom operators, you could simply make them functions and just use map:

const double = (x: number) => x * 2;
const triple = (x: number) => x * 3;

timer(0, 1000).pipe(
  take(4),
  map(x => (x <= 1 ? double(x) : triple(x)))
);

If the modifications come from an observable source, you can use a function that returns an observable instead with mergeMap:

const double$ = (x: number) => of(x * 2);
const triple$ = (x: number) => of(x * 3);

timer(0, 1000).pipe(
  take(4),
  mergeMap(x => x <= 1 ? double$(x) : triple$(x))
);

StackBlitz

城歌 2025-02-11 16:35:14

它可以进一步归结为

timer(0, 1000).pipe(
  take(4),
  map(x => x*(x <= 1?2 : 3))
);

It can be further boiled down to this

timer(0, 1000).pipe(
  take(4),
  map(x => x*(x <= 1?2 : 3))
);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文