Get last value from incomplete observable
observable, rxjs, rxjs5
Solution
I had a solution for `ReplaySubject(2)` that 'drains' the sequence to get the latest element and if the sequence is empty simply takes the last element, yet, it was cumbersome and did not scale well (for example, if you decide to increase the replay size to 3). I then remembered that Replay/Behavior subjects tend to be hard to manage when they are piped. The simplest solution to that is to create a 'shadow' sequence and pipe your ReplaySubject into it (instead of creating it by transformation/operation on your ReplaySubject), hence:
var subject$ = new Rx.ReplaySubject(3);
var lastValue$ = new Rx.ReplaySubject(1);
subject$.subscribe(lastValue$); // short hand for subject$.subscribe(v => lastValue$.next(v))
lastValue$.take(1).toPromise().then(...);
========== Old solutions, ignoring the ReplaySubject(2) =================
After reading the comment below, the correct code is:
Rx.Observable.combineLatest(possiblyReplayedIncomplteObservable).take(1).subscribe(...)
and not
Rx.Observable.combineLatest(possiblyReplayedIncomplteObservable).subscribe(...)
This is due to the fact the promise is a "one time" observable. I think the `toPromise()` code resolves the result only on completion.
The `take(1)` will not affect your original stream since it operates on the new stream which is created by `combineLatest`.
And actually, the simplest way is:
possiblyReplayedIncomplteObservable.take(1).toPromise().then(...)
Problem
There is an incomplete observable which can have or not have a replay of n values. I would like to get the last value from it - or just the next one if there is none yet. This works for first available value with `first()` and `take(1)` (example): ``` possiblyReplayedIncomplteObservable.first().toPromise().then(val => ...); ``` But for the last value both `last()` and `takeLast(1)` wait for observable completion - not the desirable behaviour here. How can this be solved? Is there a specific operator for that?