Get the latest value of an Observable and emit it immeditely

E-Kami picture E-Kami · May 3, 2016 · Viewed 60.7k times · Source

I'm trying to get the latest value of a given Observable and get it to emit immediately once it's called. Given the code below as an example:

return Observable.just(myObservable.last())
    .flatMap(myObservable1 -> {
        return myObservable1;
    })
    .map(o -> o.x) // Here I want to end up with a T object instead of Observable<T> object

This does not work because by doing this the flatMap will emit myObservable1 which in turn will have to emit to reach the map. I don't know if doing such thing is even possible. Do anyone have any clue on how to achieve this goal? Thank you

Answer

MatBos picture MatBos · May 4, 2016

last() method will not be of any help here as it waits for the Observable to terminate to give you the last item emitted.

Assuming that you do not have the control over the emitting observable you could simply create a BehaviorSubject and subscribe it to the observable that emits the data that you want to listen and then subscribe to the created subject. Since Subject is both Observable and Subscriber you will get what you want.

I think (do not have the time to check it now) you may have to manually unsubscribe from the original observable as the BehaviorSubject once all of his subscribers unsubscribe will not unsubscribe automatically.

Something like this:

BehaviorSubject subject = new BehaviorSubject();
hotObservable.subscribe(subject);
subject.subscribe(thing -> {
    // Here just after subscribing 
    // you will receive the last emitted item, if there was any.
    // You can also always supply the first item to the behavior subject
});

http://reactivex.io/RxJava/javadoc/rx/subjects/BehaviorSubject.html