从内部flatMap通知

时间:2016-12-06 10:09:06

标签: rxjs rxjs5

这是一个相当复杂的样本:

主:

this.runInstructionAndGetResult().subscribe({
      next: val => console.log(`NEXT VALUE: ${val}`),
      error: val => console.log(`ERROR VALUE: ${val}`),
      complete: val => console.log(`COMPLETE`)
    });

观测量:

public runInstructionAndGetResult(): Observable<string> {
    return this.runAnInstruction()
        .flatMap((data) => {
            console.info("flatMap of runAnInstruction:", data);
            return this.getInstructionExecutionStatusInPolling()
                .filter(data => data != "Polling")
                .take(1)
                .flatMap((data) => {
                    console.info("flatMap of getInstructionExecutionStatusInPolling:", data);
                    return this.getInstructionResult();
                }).map((data) => {
                    console.info("Map of getInstructionResult:", data);
                    return data;
                });
        });
  }

  public runAnInstruction(): Observable<string> {
    return Observable.of("StartRun");
  }

  public getInstructionResult(): Observable<string> {
    return Observable.of("FinalResult");
  }

  public getInstructionExecutionStatusInPolling(): Observable<string> {
    return Observable.interval(1000)
        .concatMap(data => {
            return this.getInstructionExecutionStatus();
        });
  }

  public getInstructionExecutionStatus(): Observable<string> {
    return Observable.of("Polling", "Terminate");
  }

这里插入: https://plnkr.co/edit/c1cahMtVARQnLgnHWlEe?p=preview

主要问题是我只想通知外部内流的“演变”。

现在,只有当所有内部flatMap都完成后,我们才会在main上发生“next”事件。

如何获取通知?如何在轮询期间向主流发出显式值?

感谢。

1 个答案:

答案 0 :(得分:1)

我找到了一个分享的解决方案。

这里的plunker更新了:

https://plnkr.co/edit/c1cahMtVARQnLgnHWlEe?p=preview

基本上我使用:https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/create.md

创建一个简单的observable

然后我以编程方式调用next方法并最终完成:

 public runInstructionAndGetResult(): Observable<string> {
    return Observable.create((ops)=> {
      ops.next(1);
      this.runAnInstruction()
        .concatMap((data) => {
            ops.next(2);
            console.info("flatMap of runAnInstruction:", data);
            return this.getInstructionExecutionStatusInPolling()
                .filter(data => data != "Polling")
                .take(1)
                .concatMap((data) => {
                    ops.next(3);
                    console.info("flatMap of getInstructionExecutionStatusInPolling:", data);
                    return this.getInstructionResult();
                }).map((data) => {
                    console.info("Map of getInstructionResult:", data);
                    ops.next(4);
                    ops.complete();
                    return data;
                });
        }).subscribe();
        });
  }