首页 > 解决方案 > Observable 将 groupby 的行为与 combinelatest 相结合并表现出“外连接”行为

问题描述

我正在尝试使用反应范式来创建一个可观察的对象,其行为类似于“group by”和 combinelatest 的组合。我有两个具有共享连接键的源 observable,如下面的两个数据结构所示。

class Foo
{
    string Key;
    string Funky;
}

class Bar
{
    string Key;
    string Town;
}

我想要的是一个可观察到的,它可以为我提供这两个加入 InstrumentID 的最新组合。最终结果应类似于:

class Target
{
   string Key;
   string Funky;
   string Town;
}

并表现出类似“外连接”的行为,这意味着产生新“键”的第一个序列将产生一个目标类,另一端为空,然后一旦另一端也产生相同的连接键,两者的最新只要给定键的任一序列中有新值,就会产生边。

标签: rxjsrx-javareactive-programmingsystem.reactive

解决方案


假设您的foo$流发出 Foo 类型的值,而bar$流发出Bar. 以下是如何组合它们:

combineLatest([
  foo$,
  bar$
    // use startWith(null) to ensure combineLatest will emit as soon as foo$ emits, not waiting for bar$ to emit its first value
    .pipe(startWith(null))
]).pipe(
  map(([foo, bar]) => ({
    // always keep all properties from foo
    ...foo,
    // only add properties from bar if it has the matching Key
    ...(bar && bar.Key === foo.Key ? bar : null)
  }))
)

推荐阅读