在可观察的生命周期中保留变量

时间:2019-08-06 07:19:49

标签: angular typescript rxjs

如何在整个可观察的生命周期中保留scriptId? 如果我尝试使用不同的ID两次运行此代码,则sId var将在可观察范围内更改并破坏代码。

SendScript (event, scriptId) { 
    //THINGS HAPPEN...`enter code here`
    //Setting the id of the script
      let sId = scriptId; <------
    // This is changing every time i send the script
    // so later on in my observable this variable changing and breaking the 
    // uniqness of the script.
    //How can I do this correctly to use this id all the observable life and 
    //it completes ?
      this.scriptObs$ = from(scriptLinesObject)
        .pipe(
          concatMap((SL: ScriptLine) => {
            // more code here
            //I want to use the id here!   <------
            if(something) {
              return x;
            }
            else if(somethingElse) {
              return y;
            }
          }),
        ).subscribe(
          (res: any) => {
            // more code here
            //I want to use the id here! <------
          },
          (err) => { },
          () => { 
            // more code here
            //I want to use the id here! <------
           },
        );
    } 
  }

@Robert garcia

  

如果您需要维护变量,请给它更大的范围,而不是一个   本地范围

有什么区别?如果我有一个全局变量并且更改了它,我的可观察对象仍将使用“更新值”而不是“起始值”(我需要)。 如果我错了,请修复我。

1 个答案:

答案 0 :(得分:2)

您不必一定要在每个library(shiny) library(ipc) library(future) plan(multiprocess) ui <- shinyUI(fluidPage( textOutput("var") )) server <- shinyServer(function(input, output, session) { q <- shinyQueue() q$consumer$start(100) val <- reactiveVal(T) future({ for(i in 1:10){ Sys.sleep(.1) if(val()){ #if(i<6){ q$producer$fireEval(print(index), list(index=i)) if(i==5) q$producer$fireAssignReactive("val", F) } else { q$producer$fireEval(print(index), list(index=i*10)) } } }) NULL output$var <- renderText(val()) }) shinyApp(ui = ui, server = server) 函数调用thank to closure中保留sId的值,箭头函数可帮助您将Observable内部的上下文绑定到SendScript()函数,因此SendScript()的值始终存储在每个sId函数调用中并确定范围:

SendScript()

此外,由于您使用的是concatMap(),因此请确保其中返回的x和y是可观察的。