Home > OS >  How to take the first Input every 3 seconds in RxJs?
How to take the first Input every 3 seconds in RxJs?

Time:10-31

I have two Components that call a method in a service. Both make several calls but i only want to track one call and it should be the first one. In my example i get only one call but it is the last one, i want the first one.

Component 1:

Calling this method several times

this.myService.writexy('1')

Component 2:

Calling this method several times

this.myService.writexy('2')

MyService:

sub = new ReplaySubject(1);
  debounced = this.sub.pipe(
    debounce(() =>interval(3000))
  )

constructor() {
    this.debounced.subscribe((val) => {
      console.log(val);
    });
  }

writexy(x) {
    this.sub.next(x);
  }

if the stream input is 1 2 the Output should be 1

CodePudding user response:

You probably want to use throttle. It behaves similar to debounce but it emits the first value and suppresses further emits during the specified interval.

const debounced = this.sub.pipe(
  throttle(val => interval(3000))
)

Or even shorter: throttleTime.

const debounced = this.sub.pipe(
  throttleTime(3000)
)
  • Related