展平嵌套的Observable [英] Flattening nested Observables

查看:129
本文介绍了展平嵌套的Observable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我陷入了嵌套的可观察地狱,可以用手做。

I'm a stuck in nested observable hell and could do with a hand.

我有以下代码块

return this.findUser(term).map( users => {
  return users.map( user => this.getLastLogin(user.user_id).map( last_login => {
    user.last_login = last_login;
    return user;
  }));
});

findUser 返回 Observable< User []> getLastLogin 返回 Observable< number>

我基本上希望获取一个用户列表,然后用另一个值的信息更新它。

I'm basically hoping to fetch a list of users and then update this with the information from another value.

现在,上面的代码返回< Observable< Observable< User> []>

Right now the code above is returning <Observable<Observable<User>[]>.

我想我可以用 flatMap 替换初始的 map ,但这会将对象转换为< Observable< Observable< User>>

I thought I could replace the initial map with flatMap but this turns the object into <Observable<Observable<User>>.

RxJS文档有点难以破译,所以我不确定<$ c的组合$ c>开关, forkJoin flatMap 会让我得到我需要的东西。

The RxJS documentation is a little hard to decipher so I'm not sure what combination of switch, forkJoin or flatMap will get me to what I need.

我希望返回 Observable< User []> 。有没有人能指出我正确的方向?

I'm hoping to return Observable<User[]>. Could anyone point me in the right direction?

推荐答案

实际上,你不需要 forkJoin() 也不是 switch()这样做。

Actually, you don't need forkJoin() nor switch() to do this.

一般来说,你想要更新通过另一个异步调用,用户数组中的每个用户。

In general, you want to update each user in the array of users by another async call.

我这样做:

var source = findUser('term')
    .mergeAll()
    .mergeMap(user => getLastLogin(user.user_id)
        .map(last_login => {
            user.last_login = last_login;
            return user;
        })
    )
    .toArray();

source.subscribe(val => console.log(val));

运营商 mergeAll() 将高阶Observable转换为单个observable。在这种情况下,它接受所有用户的数组并逐个重新发出它们。然后 mergeMap()发出使用 last_login 日期更新的用户。最后,我使用 toArray()将单个用户转换为一个整体发出的大型数组(如果要发出单个用户,可以删除此运算符) 。

Operator mergeAll() converts a higher-order Observable into single observables. In this case it takes the array of all users and re-emits them one by one. Then mergeMap() emits users updated with the last_login date. At the end I used toArray() to transform single users into one large array that is them emitted as whole (you can remove this operator if you want to emit single users instead).

请注意,当您使用 return users.map(...)时,您使用的是 Array.map()返回一个数组而不是返回Observable的RxJS中的 map()。我认为使用单个对象通常更容易使用对象数组。

Note that when you used return users.map(...) you were using Array.map() that returns an array and not map() from RxJS that returns an Observable. I think working with single objects is usually easier that with arrays of objects.

查看现场演示: https:// jsbin.com/naqudun/edit?js,console

这打印到控制台:

[ { name: 'foo',
    user_id: 42,
    last_login: 2016-11-06T10:28:29.314Z },
  { name: 'bar',
    user_id: 21,
    last_login: 2016-11-06T10:28:29.316Z } ]

这篇关于展平嵌套的Observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆