To get the last emitted value from an Observable, you can use the last
operator. The last
operator filters the values emitted by the source Observable and only emits the last value before the Observable completes.
Here’s an example of how you can use last
operator in RxJS to get the last emitted value:
import { Observable } from 'rxjs';
const observable = new Observable((observer) => {
observer.next(1);
observer.next(2);
observer.next(3);
observer.complete();
});
observable.pipe(
last()
).subscribe((value) => {
console.log(value); // Output: 3
});
In this example, we create an Observable using the Observable
constructor and emit three values using the next
method. After emitting the values, we call the complete
method to indicate that the Observable has completed.
We then use the last
operator with the pipe
method to filter the emitted values and only emit the last value. Finally, we subscribe to the resulting Observable and log the last emitted value to the console.
The output of the above code will be 3
, which is the last emitted value from the Observable.