这个 isStable API 的实现是 switchMap
和 debounce
,[timer](https://www.learnrxjs.io/learn-rxjs/operators/creation/timer)
等操作符的组合。
首先看 timer 的例子:
// RxJS v6+import { timer } from 'rxjs';//emit 0 after 1 second then complete, since no second argument is supplied// timer 调用返回一个 Observable,它订阅后在1秒钟后 emit 一个整数 0,const source = timer(1000);//output: 0const subscribe = source.subscribe(val => console.log(val));
从 console 输入看,的确是订阅后一秒,发射整数 0:
timer 的第二个参数为工夫距离,上面的例子:
// RxJS v6+import { timer } from 'rxjs';/* timer takes a second argument, how often to emit subsequent values in this case we will emit first value after 1 second and subsequent values every 2 seconds after*/const source = timer(1000, 2000);//output: 0,1,2,3,4,5......const subscribe = source.subscribe(val => console.log(val));
从输入可能看出,1秒后发射整数0,而后每隔两秒,发射一个递增的整数:
再看 debounce:
Discard emitted values that take less than the specified time, based on selector function, between output.
如果在 selector function 指定的工夫距离内 emit 出的数据,将会被抛弃。
debounce 也返回一个新的 Observable,接管一个函数作为输出参数。
debounce(durationSelector: function): Observable
上面的代码只会在管制台上看到 of 参数里最初一个元素被打印进去:
// RxJS v6+import { of, timer } from 'rxjs';import { debounce } from 'rxjs/operators';//emit four stringsconst example = of('WAIT', 'ONE', 'SECOND', 'Last will display');/* Only emit values after a second has passed between the last emission, throw away all other values*/const debouncedExample = example.pipe(debounce(() => timer(1000)));/* In this example, all values but the last will be omitted output: 'Last will display'*/const subscribe = debouncedExample.subscribe(val => console.log(val));
下列代码:
// RxJS v6+import { interval, timer } from 'rxjs';import { debounce } from 'rxjs/operators';//emit value every 1 second, ex. 0...1...2const interval$ = interval(1000);//raise the debounce time by 200ms each secondconst debouncedInterval = interval$.pipe(debounce(val => timer(val * 200)));/* After 5 seconds, debounce time will be greater than interval time, all future values will be thrown away output: 0...1...2...3...4......(debounce time over 1s, no values emitted)*/const subscribe = debouncedInterval.subscribe(val => console.log(`Example Two: ${val}`));
输入:
首先,第 6 行的 interval(1000),订阅之后,每隔1秒会产生一个递增的整数值。
这个整数值,通过 pipe 流入到第 8 行的 debounce 操作符。如果一个数据是在 debounce 输出参数 value
代表的工夫距离之内 emit 的,则该数据会被抛弃,这就是 debounce
Operator 所起的作用。
每隔1秒产生的整数,进入到 debounce 操作符内,debounce 监控的工夫距离通过函数 (val) => timer(val * 200 ) 函数指定,因而 debounce 监控的工夫距离顺次为 200,400,600,800,1000毫秒,以此类推。当 1200 毫秒之后,interval 每隔 1 秒产生的数值,因为 1 秒的工夫距离曾经落在了 debounce 从 1200 毫秒开始的工夫距离内,所以从 5 开始的整数会全副被 debounce 操作符抛弃掉。