Search code examples
rxjsiif

rxjs conditional startWith , endWith using iif operator


Still figuring rxjs out and its a great library (have to admit). Given that we have this source and booleans.

let source = [0,1,2,3,4,5,6,7,8,9];
let swEnabled = false;
let ewEnabled = false;

And we would like to conditionally enable startwith and endwith operators based on swEnabled and ewEnabled to the source.....

source.pipe(
        iif(() => swEnabled,startWith(1000),),
        iif(() => ewEnabled,endWith(1000),),
        ).subscribe( 
        (n)=>{
               console.log(n);
           });

but no joy..... anyone can provide an example of this? Maybe the approach is wrong. Or can you suggest some alternative approach ?

Thanks in advance


Solution

  • You can conditionally build an array of operators as follows:

    import { MonoTypeOperatorFunction, of } from 'rxjs';
    import { pipeFromArray } from 'rxjs/internal/util/pipe';
    import { endWith, startWith } from 'rxjs/operators';
    
    let source = of(0,1,2,3,4,5,6,7,8,9);
    let swEnabled = false;
    let ewEnabled = false;
    let operators: MonoTypeOperatorFunction<number>[] = []
    
    if (swEnabled) {
      operators.push(startWith(1000))
    }
    
    if (ewEnabled) {
      operators.push(endWith(1000))
    }
    
    source.pipe(pipeFromArray(operators)).subscribe(e => console.log(e))
    

    There is currently an open issue about not being able to use the spread syntax inside the pipe. If that issue gets fixed, then you will no longer need the pipeFromArray function and the solution can be simplified to source.pipe(...operators).

    Re iif: Note that the iif function is an Observable constructor function and not an operator function. That means that you cannot use iif as an operator inside pipe() as you have shown. By observing the RxJx reference page, you can see that there are two sections, amongst others, titled index and operators. Only the functions under operators can be used directly within the pipe(). The functions under index can be used to construct source Observables.

    Re startWith and endWith: These two functions are operator functions (meant to be used inside pipe) and not Observables. The iif function expects an Observable as the second and third argument.