0
votes

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? (e.g. 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.

3

3 Answers

4
votes

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.

1
votes

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);
0
votes

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);