简体   繁体   English

如何用 repeat(delay) 替换已弃用的 repeatWhen(notifier)

[英]How to replace the deprecated repeatWhen(notifier) with repeat(delay)

While testing, refactoring and future-proofing a customers project, I stumbled over this little deprecation notification:在测试、重构和面向未来的客户项目时,我无意中发现了这个小小的弃用通知:

Will be removed in v9 or v10.将在 v9 或 v10 中删除。 Use repeat's delay option instead.请改用重复的延迟选项。

repeatWhen(notifier: (notifications: Observable) => Observable): MonoTypeOperatorFunction repeatWhen(notifier: (notifications: Observable) => Observable): MonoTypeOperatorFunction

Simple enough, right?很简单,对吧? But when I tried, I didn't find a simple way to do so.但是当我尝试时,我没有找到一种简单的方法来做到这一点。 I have a rough idea how I could hack it.我有一个粗略的想法如何破解它。 But that's not exactly what I'd like to hand over to a customer as "improved" code.但这并不是我想作为“改进”代码移交给客户的内容。 So what obvious path do I fail to see, that leads from this (straight out of the rxjs documentation):那么我没有看到什么明显的路径,导致这个(直接出自 rxjs 文档):

import { of, fromEvent, repeatWhen } from 'rxjs';

const source = of('Repeat message');
const documentClick$ = fromEvent(document, 'click');

***const result = source.pipe(repeatWhen(() => documentClick$));***

result.subscribe(data => console.log(data))

to this:对此:

import { of, fromEvent, repeat } from 'rxjs';

const source = of('Repeat message');
const documentClick$ = fromEvent(document, 'click');

const result = source.pipe(repeat({ delay: ??? () => documentClick$) });

result.subscribe(data => console.log(data))

How to switch an option that accepts a number into an option that repeats whenever the event happens?如何将接受数字的选项切换为在事件发生时重复的选项? Well, as said, I have an idea how to achieve it, but it would be incredibly ugly.好吧,如前所述,我知道如何实现它,但它会非常难看。 So what am I missing?那我错过了什么?

You almost got it right, just remove the question marks:)你几乎做对了,只需删除问号:)

source.pipe(repeat({ delay: () => documentClick$ }));

This basically says "Whenever source completes, subscribe to documentClick$ and whenever this ( documentClick$ ) emits, re-subscribe to source .这基本上是说“每当source完成时,订阅documentClick$并且每当这个( documentClick$ )发出时,重新订阅source

Did you want to do more with that?你想用它做更多吗? I didn't fully understand your last paragraph.我没有完全理解你的最后一段。

In my little example, where a mouse click is faked by a timer, I get an emission every 2 seconds:在我的小例子中,鼠标点击是由计时器伪造的,我每 2 秒发射一次:

import { of, repeat, timer } from 'rxjs';

const source = of('Repeat message');
const documentClick$ = timer(2000);

const result = source.pipe(repeat({ delay: () => documentClick$ }));

result.subscribe((data) => console.log(data));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM