【问题标题】:RxJS - Properly merging two arrays from two seperate $http streamsRxJS - 正确合并来自两个单独的 $http 流的两个数组
【发布时间】: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


    【解决方案1】:

    您不应该改变流中的数据,但 boxer.fights = 会这样做。 您也可以通过forkJoin 将流组合在一起,因为它们不相互依赖。

    尝试使用地图运算符:

    const boxersWithFights2 = forkJoin([boxersStream, fightsStream]).pipe(
        map(([boxers, fights]) => {
          return boxers.map(boxer => ({
            ...boxer,
            fights: fights.filter(fight => fight.user_id === boxer.user_id ||fight.opponnent_id === boxer.user_id ),
        })),
    ));
    

    【讨论】:

    • 这是我所期望的答案。非常感谢
    猜你喜欢
    • 2022-01-25
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 2011-02-09
    • 1970-01-01
    相关资源
    最近更新 更多