在RXJS中可观察到的回路?

发布于 2025-02-02 12:41:16 字数 284 浏览 2 评论 0原文

这是一个令人费解的示例,但是我想知道如何在RXJS中进行以下操作:在管道中的某个部分之后,将值馈回管道的早期部分,因此它将再次处理。

of(1, 2, 3, 4, 5).pipe(
  map(x => x + 1),
  map(x => x + 1),
  filter(x => x % 2),
  // refeed after the first map but before the second
)

This is a bit of a convoluted example, but I was wondering how to do the following in RxJs: After a certain part in the pipeline, feed the value back into an earlier part of the pipeline, so it will get processed again.

of(1, 2, 3, 4, 5).pipe(
  map(x => x + 1),
  map(x => x + 1),
  filter(x => x % 2),
  // refeed after the first map but before the second
)

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

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

发布评论

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

评论(1

柏林苍穹下 2025-02-09 12:41:16

以下是您如何使用展开来执行此操作的一个示例:

function isEven(x) {
  return x % 2 == 0
}

of(1, 2, 3, 4, 5).pipe(
  map(x => x + 1),
  expand(x => of(x).pipe(
    map(x => x + 1),
    filter(isEven)
  ))
);

您可能会写递归功能以执行此操作:

function isEven(x) {
  return x % 2 == 0
}

function loopBack(x : number) {
  return of(x).pipe(
    map(x => x + 1),
    filter(isEven),
    mergeMap(loopBack),
    startWith(x)
  );
}

of(1, 2, 3, 4, 5).pipe(
  map(x => x + 1),
  mergeMap(loopBack),
);

Here's an example of how you might use expand to do this:

function isEven(x) {
  return x % 2 == 0
}

of(1, 2, 3, 4, 5).pipe(
  map(x => x + 1),
  expand(x => of(x).pipe(
    map(x => x + 1),
    filter(isEven)
  ))
);

Here's how you might write a recursive function to do this:

function isEven(x) {
  return x % 2 == 0
}

function loopBack(x : number) {
  return of(x).pipe(
    map(x => x + 1),
    filter(isEven),
    mergeMap(loopBack),
    startWith(x)
  );
}

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