Typescript: RXJS `distinctUntilChanged` 在严格模式下/第一个参数未定义时不起作用
以下代码不起作用:
let observable: Observable<{ key: number }> = of({ key: 123 });
observable.pipe(
distinctUntilChanged(undefined, v => v.key)
);
尽管存在超载:
export function distinctUntilChanged<T, K>(
comparator?: (previous: K, current: K) => boolean,
keySelector: (value: T) => K = identity as (value: T) => K
): MonoTypeOperatorFunction<T>
这是为什么?
答案#1
提供的示例不是 TypeScript 示例,因此 undefined 不能作为以下类型的第一个参数使用!请改为指定一个默认比较器并设置 keySelector!
类型定义:
import { MonoTypeOperatorFunction } from '../types';
export declare function distinctUntilChanged<T>(comparator?: (previous: T, current: T) => boolean): MonoTypeOperatorFunction<T>;
export declare function distinctUntilChanged<T, K>(comparator: (previous: K, current: K) => boolean, keySelector: (value: T) => K): MonoTypeOperatorFunction<T>;
代码:
import { of, distinctUntilChanged, Observable } from 'rxjs';
export interface TypeObj {
updatedBy: string;
data: Array<string>;
}
// A stream of updates to a given account
const accountUpdates$: Observable<TypeObj> = of(
{ updatedBy: 'blesh', data: [] },
{ updatedBy: 'blesh', data: [] },
{ updatedBy: 'ncjamieson', data: [] },
{ updatedBy: 'ncjamieson', data: [] },
{ updatedBy: 'blesh', data: [] }
);
// We only want the events where it changed hands
const changedHands$ = accountUpdates$.pipe(
distinctUntilChanged<TypeObj, string>(
(prev: string, curr: string): boolean => prev === curr,
(update: TypeObj) => update?.updatedBy
)
);
changedHands$.subscribe(console.log);
Stackblitz 演示
答案#2
实际上,你误用了 distinctUntilChanged。像下面这样重构你的代码应该就可以了:
const observable: Observable<{ key: number }> = of({ key: 123 });
observable.pipe(
distinctUntilChanged((prev, curr) => prev.key === curr.key)
);
