Search code examples
rxjsobservable

RxJS Create two observables from one obseravable


I have this:

$someObserver
   .subscribe(foo => {
      if(foo === "Bar" ) {/*Do A*/}
      else {/*Do B*/}
});

It works. What I want: achieving the same but without conditions and with more RxJS style.

Is there something to do it RxJS style?

I know 'partition' but i dont like it. I would prefer to the separation within the stream. Something like:

$someObserver
.pipe(
   split(foo => foo === 'bar') 
      tap([streamA, stream] => {
         streamA.subscribe(x => /*doA*/);
         streamB.subscribe(x => /* doB */) ;
})).subscribe();

Does something like this exists?

Thanks!


Solution

  • If you want to do basic non observable actions, just use a tap.

    import './style.css';
    
    import { rx, of, map, from, tap } from 'rxjs';
    
    const arr = [1, 1, 1, 1, 2, 2, 2, 2, 1, 2];
    
    from(arr)
      .pipe(
        tap((item: number) => {
          if (item === 1) {
            console.log(1);
          } else {
            console.log(2);
          }
        })
      )
      .subscribe();
    

    Stackblitz Demo


    If you have observable actions also, consider iif instead, for splitting the streams based on a condition.

    import './style.css';
    
    import { rx, of, map, from, concatMap, iif, tap } from 'rxjs';
    
    const arr = [1, 1, 1, 1, 2, 2, 2, 2, 1, 2];
    
    from(arr)
      .pipe(
        concatMap((item: number) => iif(
          () => item === 1,
          of(item).pipe(
            tap(() => console.log(1))
          ),
          of(item).pipe(
            tap(() => console.log(2))
          )
        ))
      )
      .subscribe();
    

    Stackblitz Demo