Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SIngle RxJava how to extract object

I can think of two ways to get the value from Single

Single<HotelResult> observableHotelResult = 
                            apiObservables.getHotelInfoObservable(requestBody);

final HotelResult[] hotelResults = new HotelResult[1];
    singleHotelResult
            .subscribe(hotelResult -> {
                hotelResults[0] = hotelResult;
            });

Or

    final HotelResult hotelResult = singleHotelResult
                                    .toBlocking()
                                    .value();

It's written in the documentation that we should avoid using .toBlocking method.

So is there any better way to get value

like image 414
Deepanshu Avatar asked Jan 14 '17 07:01

Deepanshu


People also ask

How do I extract an object from Observable?

You cannot 'extract' something from an observable. You get items from observable when you subscribe to them (if they emit any). Since the object you are returning is of type Observable, you can apply operators to transform your data to your linking.

How do you use a single RxJava?

The Single class represents the single value response. Single observable can only emit either a single successful value or an error. It does not emit onComplete event.

What is single class in RxJava?

Single is an Observable which only emits one item or throws an error. Single emits only one value and applying some of the operator makes no sense.

What is blockingGet?

blockingGet() Waits in a blocking fashion until the current Single signals a success value (which is returned) or an exception (which is propagated). void. blockingSubscribe() Subscribes to the current Single and blocks the current thread until it terminates.


1 Answers

Even it is not recommended to block it (you should subscribe), in RxJava v2 the method for blocking is blockingGet(), it returns the object immediately.

like image 61
dmarquina Avatar answered Sep 18 '22 17:09

dmarquina