RxJS 排队依赖任务 [英] RxJS queueing dependent tasks

查看:56
本文介绍了RxJS 排队依赖任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的数组

{
    parent: [
        {
            name: 'stu',
            children: [
                {name: 'bob'},
                {name: 'sarah'}    
            ]
        },
        { 
          ...
        }
    ]
}

并且我想循环遍历每个父级并依次循环遍历他们的子级,这样在所有子级都处理完毕之前我不会启动下一个父级(一些长的异步过程),我该如何使用 RxJS 执行此操作?

and I want to cycle through each parent and cycle through their children in series, so that I don't start the next parent until all the children have been processed (some long asynchronous process), how do I do this with RxJS?

我已经尝试过:

var doChildren = function (parent) {
    console.log('process parent', parent.name);
    rx.Observable.fromArray(parent.children)
    .subscribe(function (child) {
        console.log('process child', child.name);
        // do some Asynchronous stuff in here
    });
};

rx.Observable.fromArray(parents)
.subscribe(doChildren);

但是我让所有的父母都退出,然后所有的孩子都退出了.

But I get all the parents logging out and then all the children.

推荐答案

concatMap 在这里效果更好.因为如果迭代子节点是异步的,子节点的顺序就会混乱.concatMap 可以保证一次完成一个父节点.

concatMap works better here. Because if iterating children is async, the order of child will be messed up. concatMap can ensure to finish one parent at a time.

Rx.Observable.from(parents)
  .concatMap(function (p) {
    return Rx.Observable.from(p.children)
  })
  .subscribe();

这篇关于RxJS 排队依赖任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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