【问题标题】:DistinctUntilChange not working with switchMap?DistinctUntilChange 不能与 switchMap 一起使用?
【发布时间】:2022-01-04 21:23:21
【问题描述】:

我正在尝试实现 rxjs 函数 distinctUntilChanged 但没有工作...

   public searchVal(val: string) {
        this.suggestions = (new Observable((observer: Observer<string>) => {
          observer.next(val);
        })).pipe(
          takeUntil(this.destroy$),
          distinctUntilChanged(),
          switchMap((query: string) => {
            if (query) {
              console.log('query query' , query) 
            }
            return of([]);
          })
        );
      }

但这不起作用我不知道为什么?我也设置了 debounceTime 但它也不起作用?

我的计划是不发送相同的值。

【问题讨论】:

  • 你订阅了吗?

标签: angular typescript rxjs


【解决方案1】:
new Observable((observer: Observer<string>) => {
  observer.next(val);
})

这只是 of(val) 除了完成 observable。此外,根据经验,takeUntil 运算符应该最后出现。这会将您的代码更改为

public searchVal(val: string) {
  this.suggestions = of(val).pipe(
    distinctUntilChanged(),
    switchMap(query => of([])),
    takeUntil(this.destroy$),
  );
}

但是,这根本不像您认为的那样。每次调用 searchVal 时,都会创建一个新的 observable 并将其分配给 suggestions,从而使 distinctUntilChanged 无用,因为只有一个值会流过管道。

你更可能想做的是创造

private readonly input$ = new Subject<string>();

public readonly suggestions$ = defer(() => this.input$).pipe(
  distinctUntilChanged(),
  switchMap(() => of([])),
  takeUntil(defer(() => this.destroy$)),
);

然后

public searchVal(val: string) {
  this.input$.next(val);
}

defer() 调用只是避免申报顺序问题的一个技巧。如果您改为分配suggestions$,例如在构造函数中你不需要defers。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    • 2017-04-14
    • 2016-09-16
    • 2016-04-19
    • 1970-01-01
    相关资源
    最近更新 更多