如何使用可观察管道动态更改间隔?

时间:2018-12-20 01:35:47

标签: angular typescript rxjs observable

这是一种方法。单击按钮即可更新intervalValue。该值经常更改。

intervalValue: number; 
intervalValue: Observable<number>; // also tried this. but interval method is looking for a number 

  ngOnInit() {

    interval(intervalValue)
    .pipe( 
              debounceTime(150),
              distinctUntilChanged(),
              tap(() => { 
                    ... 
                }), 
              startWith({}),
        switchMap(() => { 
         ... 
        }),
        map(data => {
          ... 
          return data.content;
        }),
        catchError(() => {
         ... 
        })
        ).subscribe(data => this.data = data);
}                                                       

但是,当intervalValue发生变化时,interval仍保持其初始值。 intervalValue的值更改时,如何更改间隔?

1 个答案:

答案 0 :(得分:1)

您需要从Intervalue流开始

const intervalValue=of(Math.random()*10000)
intervalValue
    .pipe( 
              switchMap(time=>interval(time))
              debounceTime(150),
              distinctUntilChanged(),
              tap(() => { 
                    ... 
                }), 
              startWith({}),
        switchMap(() => { 
         ... 
        }),
        map(data => {
          ... 
          return data.content;
        }),
        catchError(() => {
         ... 
        })
        ).subscribe(data => this.data = data);