这是一个复杂情况的简化,如果值无效,则可以过滤数组中的某些可观察对象。问题在于,过滤后的可观察对象不允许其他对象完成合并。哪种运营商或方法可以处理这种情况,从而允许在订阅中记录有效数据?
// 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();
如果将值更改为67,则所有可观察对象将显示数据。
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
。
您可以将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();