Matthieu Dsprz
Matthieu Dsprz

Reputation: 477

RxJS - race between click and timer

I struggle to create an observable that would emit each time I click or, if I don't click, emit each second and whose timer would be reset each time I click.

I almost achieved what I want with a simple merge but I don't know how to reset the timer each time I click.

import { fromEvent, merge, timer } from "rxjs";
import { debounceTime, map } from "rxjs/operators";

const click$ = fromEvent(document, "click");

merge(click$, timer(0, 1000))
  .pipe()
  .subscribe(console.

Upvotes: 1

Views: 437

Answers (1)

martin
martin

Reputation: 96899

It sounds like you're looking for switchMap and startWith.

click$.pipe(
  startWith(null),
  switchMap(() => timer(0, 1000))
).subscribe(console.log);

Upvotes: 3

Related Questions