I have an observable. I’m attempting to convert it to a promise using the lastValueFrom
method.
const obs = timer(1000).pipe(
map(() => `First Value!`),
startWith('But StartWith this')
);
lastValueFrom(obs).then(console.log);
Outputs:
First Value!
This is not what I was expecting because startWith
literally means, start-with. But when I subscribe it, it behaves correctly:
obs.subscribe(console.log);
outputs:
But Start With This
First Value!
Here is the stackblitz.
How to circumvent this issue and get last emitted value as a promise from an observable?
Edit 1: It is interesting that this thing never resolves:
const obs = new Subject().asObservable().pipe(startWith('startWith'));
lastValueFrom(obs).then(console.log);
2
Answers
If I am reading it correctly, then
lastValueFrom
obs isFirst Value
since youstartWith
a new value.In your first example,
lastValueFrom
makes the valueFirst Value
be the last value from your source observable.In your second example, nothing is emitted because the observable you create is a so called "cold" observable that never emits a value and therefor never completes. To quote the RxJS docs:
If you add
take(1)
to the pipe in your second example, it "magically" works. 🙂