首页 > 解决方案 > 递归执行 rxjs 可观察函数

问题描述

我是 RxJs 的新手。我正在尝试递归运行可观察函数,但没有运气。我想按这个顺序打印。

表单文本框图标文本区域

这是我到目前为止所尝试的。任何帮助将不胜感激。

const args = {
  name: 'form',
  children: [{
    name: 'textbox',
    children: [{
      name: 'icon',
      children: []
    }]
  }, {
    name: 'textarea',
    children: []
  }]
};

import { of, from, Observable, concat } from 'rxjs'; 
import { map, concatAll, combineAll } from 'rxjs/operators';

const render = (component) => {
 return new Observable<any>(observer => {
   console.log(component.name);
   concat(...component.children.map(x => render(x)))
   .subscribe(() => observer.next());
 });
};

render(args).subscribe(() => console.log('done'));

标签: rxjs

解决方案


这给出了正确的顺序。如果我遗漏了什么,请发表评论:

const { of, concat } = rxjs;

const args = {
  name: 'form',
  children: [
    {
      name: 'textbox',
      children: [
          {
            name: 'icon',
            children: []
          }
        ]
      },
    {
      name: 'textarea',
      children: []
    }
  ]
};

const render = (component) => concat(of(component), ...component.children.map(render));

render(args).subscribe(({name}) => console.log(name));
<script src="https://unpkg.com/@reactivex/rxjs@6.4/dist/global/rxjs.umd.js"></script>


推荐阅读