Home > Software engineering >  How do i limit the calling of a function - Accept behaviourSubject.next only onetime for 2000ms in A
How do i limit the calling of a function - Accept behaviourSubject.next only onetime for 2000ms in A

Time:10-31

I have a Component that by clicking a Button calls a Method in a Service.

public wasClicked(){
    this.myService.writexy('1')
  }

The Service has a BehaviourSubject and the Method that was called, that logs some Output. I want that it logs only one time in 2000ms even if the Button was clicked several times.

sub = new BehaviorSubject(1);

writexy(x){
    this.sub.next(x)
    this.sub.pipe(
      throttle(val => interval(2000)),
      //debounce(val => interval(6000)),
      //debounceTime(2000),
      take(1)
    ).subscribe(() =>  console.log('2'))

As you can see I have tried throttle, debounce and debounceTime, but it keeps printing '2' as often as I click the Button. I have also tried to use a ReplaySubject with no success. What am I doing wrong?

CodePudding user response:

The problem is you're recreating a new Observable every time writexy is called, so every new Observable will have its own, new debounceTime that has never run before. You need to move the debounceTime out so it's maintained across all calls. That might look something like this:

// Script

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  sub = new BehaviorSubject(1);
  debounced = this.sub.pipe(debounceTime(2000));

  ngOnInit() {
    this.debounced.subscribe(() => {
      console.log('2');
    });
  }

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


// Template

<button (click)="writexy(9)">Button</button>

Here is a example StackBlitz (I have no idea how long that link will live for).

  • Related