【发布时间】:2020-09-19 14:53:34
【问题描述】:
目前正在学习 RxJS,我不会撒谎,我很难理解它,尤其是“如果我们有 promises,为什么我们还要使用” 但现在我想我迈出了一小步。
我知道我应该避免嵌套订阅。 尝试编写尽可能短的代码以将两个流合并为单个变量。
所以我有两个模拟流结果的数组,我想加入它们。 Fights 数组应该成为 boxers 对象中的新 obj 数组
const boxers = [
{
user_id:1,
first_name:'Lennox ',
last_name:'Lewis',
nationality:"UK"
},
{
user_id:2,
first_name:'Mike',
last_name:'Tyson',
nationality:'USA'
},
{
user_id:3,
first_name:'Riddick',
last_name:'Bowe',
nationality:'USA'
},
];
const fights = [
{
fight_id:1,
user_id:1,
opponnent_id:2,
winner_id:1,
venue:'Memphis Pyramid, Tennessee'
}
]
然后我写了代码:
const boxersWithFights2 = boxersStream.pipe(
flatMap(boxers => {
return fightsStream.pipe(
flatMap(fights => {
boxers.map(boxer => boxer.fights = fights.filter(fight => fight.user_id === boxer.user_id ||fight.opponnent_id === boxer.user_id ))
return boxers;
})
)
}
));
令人惊讶的是,这按预期工作。 当我订阅 boxersWithFights 时,它会使用正确映射的对象来控制台记录我。 所以它可能在从外部 api 返回时也可以工作,但是我当然需要另一个 map() 运算符。
我的问题:这段代码写得好吗?能不能写得更干净优雅?
我也知道我可以更轻松地做到这一点,例如forkJoin,但我真的很想测试 flatMap(mergeMap) 运算符。
【问题讨论】:
标签: javascript typescript rxjs reactive-programming