0

How can I preserve scriptId all over the observable lifecycle ? If I try to run this code twice with different ids the sId var will change inside the observable and will break the code.

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

If you need to maintain the variable give it a bigger scope, not a local scope

what is the difference ? If i have a global var and I change it, my observable will still use the "Updated value" and not the "Starting value" (which I need). please fix me if I'm wrong.

noririco
  • 765
  • 6
  • 15

1 Answers1

2

You dont have to, sId value already preserved in each SendScript() function call thank to closure, the arrow function help you keep the context inside the Observable binded to the SendScript() function, so the sId value always be stored and scoped in each SendScript() function call :

SendScript (event, scriptId) { 
      ...
      let sId = scriptId;
      ...
      this.scriptObs$ = from(scriptLinesObject)
        .pipe(
          concatMap((SL: ScriptLine) => {
            console.log(sId)
            if(something) {
              return x;
            }
            else if(somethingElse) {
              return y;
            }
          }),catch
        ).subscribe(
          (x) => {
             console.log(sId)
          },
          (err) => { },
          () => { 
             console.log(sId)
           },
        );
    } 
  }

Additionally, since you using concatMap(), make sure the x and y returned within it is an Observable.

Ethan Vu
  • 2,911
  • 9
  • 25