首页 > 解决方案 > debounceTime 不适用于合并?

问题描述

我对单流和响应多值有疑问。不起作用的代码:

slugChecker<PipeInput, Out>(
  inputController: AbstractControl,
  pipeInput: Observable<PipeInput>,
  checker: (input: PipeInput & { name: string, slug: string }) => Observable<Out>,
  opt?: { debounceTime?: number; ignoreFirstValue?: boolean }
) {
  return inputController.valueChanges.pipe(
    shareReplay(1),
    debounceTime(opt?.debounceTime || 1000), // <= not works correctly
    // startWith(true),
    skip(opt?.ignoreFirstValue ? 1 : 0), // skip first check for edit mode
    switchMap(e => merge(
        of(null)
          .pipe(tap(_ => console.log('set null'))),
        of(e)
          .pipe(
            // delay(2000), <= bad idea
            tap(_ => console.log('run pipe', opt)),
            map(input => slugify(input, {
              replacement: '-',
              remove: /[*+~.()'"!:@]/g,
              locale: 'pl',
              lower: true,
            })),
            switchMap(slug => pipeInput.pipe(map(input => ({input, slug})))),
            switchMap(({input, slug}) => {
              console.log('mapped with ', {input, slug})
              return checker({...input, name: inputController.value, slug})
            }),
          )
      ),
    ))
}

我需要一个流,所以当我写入时,inputController流应该发出null。请求完成后,该值来自后端truefalse来自后端(+false有任何错误)。debounceTime由于合并,此代码草案不起作用吗?

编辑:
好的,我找到了灵魂:D


  slugChecker<PipeInput>(
    inputController: AbstractControl,
    pipeInput: Observable<PipeInput>,
    checker: (input: PipeInput & { name: string, slug: string }) => Observable<boolean>,
    opt?: {
      debounceTime?: number;
      ignoreFirstValue?: boolean,
      slugController?: AbstractControl,
    }
  ) {
    return merge(
      inputController.valueChanges.pipe(
        map(_ => null)
      ),
      inputController.valueChanges.pipe(
        shareReplay(1),
        debounceTime(opt?.debounceTime || 1000),
        map(input => slugify(input, {
          replacement: '-',
          remove: /[*+~.()'"!:@]/g,
          locale: 'pl',
          lower: true,
        })),
        switchMap(slug => pipeInput.pipe(map(input => ({input, slug})))),
        switchMap(({input, slug}) => {
          console.log('mapped with ', {input, slug})
          if (opt?.slugController) {
            opt.slugController.patchValue(slug)
          }
          return checker({...input, name: inputController.value, slug})
        }),
      )
    );
  }

有用

标签: angulartypescriptrxjs

解决方案


推荐阅读