简体   繁体   中英

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. Use repeat's delay option instead.

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):

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 .

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:

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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