skip to Main Content

Into a rxjs-Stream i want to conditionaly insert data, a delay and then the original event.

from(Array(10).keys())
  .pipe(
    map(i => ({ data: i })),
    concatMap(e => {
      if (e.data === 3) {
        return of(e)
          .pipe(
            delay(500),
          );
      }
      return of(e);
    }),
  )
  .subscribe(i => console.log(i));

This creates a delay before { data: 3 }.

But i want to emit { data: 'a' }, delay, { data: 3 }.

2

Answers


  1. You can achieve this by inserting a conditional delay before emitting the original event. Here’s how you can modify the code:

    import { from, of } from 'rxjs';
    import { map, concatMap, delay } from 'rxjs/operators';
    
    from(Array(10).keys())
      .pipe(
        map(i => ({ data: i })),
        concatMap(e => {
          if (e.data === 3) {
            return of({ data: 'a' })
              .pipe(
                delay(500),
                concatMap(() => of(e).pipe(delay(500))), // Inserting delay before emitting original event
              );
          }
          return of(e);
        }),
      )
      .subscribe(i => console.log(i));
    

    This will emit { data: ‘a’ }, followed by a delay, and then emit { data: 3 }.

    Login or Signup to reply.
  2. You can use merge method to achieve what you want :

     concatMap((e) => {
          if (e.data === 3) {
            return merge(of({ data: 'a' }), of(e).pipe(delay(500)));
          }
          return of(e);
        })
    

    Stackblitz

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search