Search code examples
rxjsreactivex

Problems with using external variables in an observable sequence


What problems could arise when using variables that are external to an observable sequence inside the sequence?

For example:

updateCar(newCar: any): Observable<any> {
    return of(...).pipe(
        switchMap(
            (value: any) => {
                if (newCar.has4Wheels && value.lovePizza) {
                    // return a 4 wheel observable
                } else {
                    // return a not 4 wheel observable
                }
            }
        ),
        switchMap(
            (value: any) => {
                if (newCar.has4Windows && !value.lovePizza) {
                    // return a 4 window observable
                } else {
                    // return a 2 window observable
                }
            }
        )
    );
}

I know the example above is weird, but i am just using it to ask the question.

What problems could arise with using newCar inside the sequence like being used in the example when it is external to the sequence? If there are no problems, great! Just feels like there is something wrong with this usage to me.


Solution

  • I think nothing (at least as far as you don't modify newCar).

    It's true that you could rewrite this and start with for example the following:

    of([whatever, newCar])
      .pipe(
        switchMap(([whatever, newCar]) => {
          ...
        })
      )
      ...
    

    But I think this isn't necessary and would make things just more complicated without any real benefit.