将两个不同类的两个不同可观察变量分组

时间:2018-10-18 09:49:15

标签: javascript typescript rxjs

我有两个Observables发出2种不同类别的数据:

1.User类:

{
"id"=>25,
"username"=>"Chris",
.. other data 
}

2.UserWebsocket类

 {
     "user_id"=>25,
     "age"=>25,
      .. other data 
  }

我想通过user_id或id属性将两个可观察对象合并和分组。这样合并和分组类型的结果是:

[User|undefined,UserWebsocket|undefined]

为了进一步说明问题,我制作了一个简单的大理石图:

enter image description here

这如何发生?

1 个答案:

答案 0 :(得分:2)

正如马丁的评论所建议的,请使用CombineLatest并为每个部分设置一个起始值。假设您有myUser$myUserWebsocket$可观察值,则可以使用以下代码将它们组合。首先,添加一个起始值并将可观察值存储在新值中。将它们与combineLatest合并。您必须订阅combined$可观察的

更新

另一种方法是使用merge并将其与withLatestFrom组合。

// Using RxJS v6+
import { merge } from 'rxjs';
import { startWith, map, withLatestFrom } from 'rxjs/operators';

// Your allready defined observables named e.g. myUser$ and myUserWebsocket$
// Add a starting value, since if user fires, websocket has no value yet.
const user$ = myUser$.pipe(
  startWith(undefined)
)
const userWebsocket$ = myUserWebsocket$.pipe(
  startWith(undefined)
)

const combined$ = merge(
  user$,
  userWebsocket$
).pipe(
  withLatestFrom(user$),
  withLatestFrom(userWebsocket$),
  map(([[merge, latestUser], latestWebsocket]) => {
    if (merge.user_id) { // merge is typeof userWebsocket, make sure user does not have user_id property
      if (latestUser && merge.user_id === latestUser.id) {
        return [latestUser, merge];
      } else {
        return [undefined, merge];
      }
    } else if (merge.id && !merge.user_id) { // merge is typeof user
      if (latestWebsocket && merge.id === latestWebsocket.user_id) {
        return [merge, latestWebsocket];
      } else {
        return [merge, undefined];
      }
    }
  })
);

combined$.subscribe([user, websocket] => {
  console.log(user, websocket);
});