角度和可观察到的反跳时间

Bru*_*ano 2 observable rxjs debounce angular

成多角4项目,我有一个函数(让我们叫它reload()),可以被其它函数调用(我们称它们A()B())在任何时间。我想对reload()A()或的最后一次调用过去的X时间(即毫秒)的执行进行反跳操作B()。我正在查看Rx.Observable.debounceand Rx.Observable.debounceTime函数,但是我不知道它们是否真的可以帮助我。

一个例子:

time 0ms: A() gets executed and it calls reload()
time 200ms: B() calls executed and it calls reload()
Since X is set to 500ms, reload() should be called only once and after 500ms.
Run Code Online (Sandbox Code Playgroud)

LLa*_*Lai 6

您可以将Subject搭配使用debounceTime。因此,既要有这两个功能A,又要B给主题发送一个值。然后,对主题流进行去抖动,以便在x时间过去之后仅发射值。

// component.ts
subject$ = new Subject();
stream$;

constructor(){
    this.stream$ = this.subject$.debounceTime(1000);
}

A(){
    this.subject$.next('some value');
}
B(){
    this.subject$.next('some value');
}

ngOnInit(){
    this.stream$.subscribe(res => {
        this.reload();
    });
}
Run Code Online (Sandbox Code Playgroud)

这是一个演示这的堆栈闪电战