0
votes

I'm working with Angular 9 / rxjs 6.5.2,

I want to get only the latest value when I subscribe to the Observable, I want the latest and not the last, because for the last, it will wait until Observable completes but in my case I want the latest at this moment.

My Code:

PS: You can test it directly in this link: https://stackblitz.com/edit/pjreww

const observable = new Observable(subscriber => {
  subscriber.next(1);
  subscriber.next(2);
  subscriber.next(3);
  setTimeout(() => {
    subscriber.next(4);
    subscriber.complete();
  }, 1000);
});

observable
  .pipe(
    //some pipe to make me take the latest value only
  )
  .subscribe({
    next(x) { console.log('got value ' + x); },
  });

Output Wanted::

3
4

Actual Output

1
2
3
4
1

1 Answers

1
votes

You can use shareReplay(1) that will always replay only the latest value emitted:

observable
  .pipe(
    shareReplay(1),
  )
  .subscribe({
    next(x) { console.log('got value ' + x); },
  });

Live demo: https://stackblitz.com/edit/pjreww-fzs5sl?file=index.ts