Chain Observable

谁说我不能喝 提交于 2021-02-07 09:29:31

问题


I have a problem with observable chaining.

My goal is to have this result : {Pagination, Process[]} and Process = { ....., Variables[]}

I'm calling a service which return an object {Pagination, Process[]} but Variables in Process are empty.

So i need to complete the process object with Variables properties.

I do :


this.processesService.getData().subscribe(() => {   // data  });
getData: Observable<any> {
   let processesResult = fromPromise( .... );

    return processesResult.pipe(

      map( (result) => { <= result is list of process without variables
        let entries = new Array();

        result.entries.map( **process** =>  {
          result.entries = entries;
          this.getCompleteProcess(**process.id**).subscribe((_process) => {
            entries.push(_process) <-- the process with Variables[] for enrich result map
          })
          return result.entries;
        })
      })
    );
}

Can you help me to resolve my problem ? i need to wait this.getCompleteProcess to populate parent object and return a complete result

thanks


回答1:


I think there are a few operators in rxjs that you could try out (e.g. forkJoin, concatMap). Otherwise what you could also do is to use the Observable.create. For example,

getData: Observable<any> {
    return Observable.create( (obs) => {
      let processesResult = fromPromise( .... ).subscribe(
      (result) => { <= result is list of process
        let entries = new Array();
        let obsArr = [];
        result.entries.forEach( **process** =>  {
          result.entries = entries;
          obsArr.push(this.getCompleteProcess(**process.id**).pipe(map((_process) => {
            entries.push(_process) <-- the process is complete and i need it to enrich result map
          });
          forkJoin(...obsArr).subscribe( ([]) => {
               obs.next(result.entries) => EMIT RESPONSE HERE
          } );
        })
      })
    );
}

Please note - I have not compiled or tested this. But basically, the idea is to create a wrapping observable which emits a value once all the logic is done. Hope this helps.



来源:https://stackoverflow.com/questions/62677272/chain-observable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!