简体   繁体   中英

How can I use concat operator in RxJS, but ignore all of the emissions from the first observable

Let's say we have 2 observables.

const obs1 = timer(1000); const obs2 = of(1,2,3)

If I'd like to wait until obs1 completes I could obviously use concat operator.

obs1.pipe(concat(obs2)).subscribe(console.log);

or

concat(obs1, obs2).subscribe(console.log);

It would work fine (the order is preserved), but the '0' emitted from the first obs would still be logged. Is there a way to force certain subscriptions' order, but ignore emissions from the given observable? (eg only values from the last observable in 'chain' should be seen).

In this particular case I know how many values to expect, so I could simply use skip/takeLast, but I'm looking for a generic solution, which doesn't require me to know the amount of elements emitted from observables.

You can use just ignoreElements() .

concat(obs1.pipe(ignoreElements()), obs2).subscribe(...)

It doesn't matter whether obs1 emits any next notifications or not. obs1 just needs to complete.

Use the combineLatest:

Example:

    import { timer, combineLatest } from 'rxjs';
   const timerOne$ = timer(1000, 4000);
   const timerTwo$ = timer(2000, 4000);
   const timerThree$ = timer(3000, 4000);
   combineLatest(timerOne$, timerTwo$, timerThree$).subscribe(
  ([timerValOne, timerValTwo, timerValThree]) => {

    console.log(Timer Three Latest: ${timerValThree}`
    );
  }
);

or

import { timer, combineLatest } from 'rxjs';

const timerOne$ = timer(1000, 4000);
const timerTwo$ = timer(2000, 4000);
const timerThree$ = timer(3000, 4000);

combineLatest(
  timerOne$,
  timerTwo$,
  timerThree$,
  // combineLatest also takes an optional projection function
  (one, two, three) => {
    return `${three}`;
  }
).subscribe(console.log);

You could either switchMap or log the values in the pipeline of just the second observable:

const obs1 = timer(1000);
const obs2 = of(1, 2, 3);

obs1.pipe(
  concat(obs2.pipe(tap(val => console.log(val))))
).subscribe();

obs1.pipe(
    switchMap(_ => obs2)
).subscribe(console.log);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM