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:
ret
What you actually want to achieve here is to take an asynchronous task and transform it to a synchronous one.
There are several ways to achieve it, each one with it's pros and cons:
Observable getData();
then a method that will get the last value immediately will look like this:public T getLastItem(){
return getData().toBlocking().first();
}
please don't use last() as it will wait for the stream to complete and only then will emit the last item.
If your stream is a network request and it didn't get any item yet this will block your thread!, so only use it when you are sure that there is an item available immediately (or if you really want a block...)
another option is to simply cache the last result, something like this:
getData().subscribe(t-> cachedT = t;) //somewhere in the code and it will keep saving the last item delivered public T getLastItem(){ return cachedT; }
if there wasn't any item sent by the time you request it you will get null or whatever initial value you have set. the problem with this approch is that the subscribe phase might happen after the get and might make a race condition if used in 2 different threads.