在 window-ref.ts 的实现里,定义了一个每隔 300 毫秒,通过 fromEvent 发射一个 resize event 的 Observable:
/**
* Returns an observable for the window resize event and emits an event
* every 300ms in case of resizing. An event is simulated initially.
*
* If there's no window object available (i.e. in SSR), a null value is emitted.
*/
get resize$(): Observable<any> {if (!this.nativeWindow) {return of(null);
} else {return fromEvent(this.nativeWindow, 'resize').pipe(debounceTime(300),
startWith({target: this.nativeWindow}),
distinctUntilChanged());
}
}
加上 distingctUntilChanged 操作符后,能过滤掉完全一致的 resize event. 上面的例子,展现了如何应用 distingctUntilChanged,将数字序列里反复的数字过滤掉。distingctUntilChanged 默认会将以后元素和前一元素做比拟。
import {of} from 'rxjs';
import {distinctUntilChanged} from 'rxjs/operators';
of(1, 1, 2, 2, 2, 1, 1, 2, 3, 3, 4).pipe(distinctUntilChanged(),
)
.subscribe(x => console.log(x)); // 1, 2, 1, 2, 3, 4
下列例子展现了如何将自定义的比拟逻辑,通过箭头函数作为参数,传入 distinctUntilChanged 里。
import {of} from 'rxjs';
import {distinctUntilChanged} from 'rxjs/operators';
interface Person {
age: number,
name: string
}
of<Person>({ age: 4, name: 'Foo'},
{age: 7, name: 'Bar'},
{age: 5, name: 'Foo'},
{age: 6, name: 'Foo'},
).pipe(distinctUntilChanged((p: Person, q: Person) => p.name === q.name),
)
.subscribe(x => console.log(x));
// displays:
// {age: 4, name: 'Foo'}
// {age: 7, name: 'Bar'}
// {age: 5, name: 'Foo'}