如何在某些可观察到的情况下将CombineLatest与过滤器一起使用?

问题描述 投票:0回答:2

这是一个复杂情况的简化,如果值无效,则可以过滤数组中的某些可观察对象。问题在于,过滤后的可观察对象不允许其他对象完成合并。哪种运营商或方法可以处理这种情况,从而允许在订阅中记录有效数据?

// RxJS v6+
import { fromEvent, combineLatest, of } from 'rxjs';
import { mapTo, startWith, scan, tap, map, filter } from 'rxjs/operators';

const userData$ = [
   of({ name: 'Joseph', age: 23}), 
   of({ name: 'Mario', age: 33}), 
   of({ name: 'Robert', age: 24}), 
   of({ name: 'Alonso', age: 25})
];

const names = ['Joseph', 'Mario', 'Robert', 'Alonso'];

combineLatest(
  names.map((name, i) => {
     return userData$[i].pipe(
         map(({name, age})=> { return{ name, age: age * 2} }),
         filter(({age}) => age < 67),
         map(({name, age})=> { return{ name: name.toLocaleUpperCase(), age} }),
     )
 })
)
   .pipe(
     tap(console.log),
   )
   .subscribe();

Sample in stackblitz

如果将值更改为67,则所有可观察对象将显示数据。

javascript rxjs pipeline redux-observable combinelatest
2个回答
1
投票

combineLatest的典型问题是,它要求所有源Observable至少发射一次,因此,如果使用filter放弃其唯一值,则combineLatest将永远不会发射任何东西。

一个简单的解决方案是确保它始终与defaultIfEmpty一起发出:

combineLatest(
  names.map((name, i) => {
    return userData$[i].pipe(
      map(({name, age})=> { return { name, age: age * 2} }),
      filter(({age}) => age < 66),
      map(({name, age})=> { return { name: name.toLocaleUpperCase(), age} }),
      defaultIfEmpty(null),
    )
  })
)

实时演示:https://stackblitz.com/edit/typescript-rsffbs?file=index.ts

如果您的实际用例使用的不是of()的其他可立即观察到的源,您可能想改用startWith


0
投票

您可以将combineLatest替换为from,因为如果流数组中的任何一项都不发光,则combineLatest不会发光

const userData$ = [
  { name: 'Joseph', age: 23 },
  { name: 'Mario', age: 33 },
  { name: 'Robert', age: 24 },
  { name: 'Alonso', age: 25 }
];

const names = ['Joseph', 'Mario', 'Robert', 'Alonso'];

from(
  userData$
)
  .pipe(
    map(({ name, age }) => { return { name, age: age * 2 } }),
    filter(({ age }) => age < 66),
    map(({ name, age }) => { return { name: name.toLocaleUpperCase(), age } }),
    tap(console.log),
  )
  .subscribe();
© www.soinside.com 2019 - 2024. All rights reserved.