11

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

Deepanshu
  • 209
  • 1
  • 2
  • 8

2 Answers2

7

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.

dmarquina
  • 3,728
  • 1
  • 28
  • 28
6

When we use toBlocking then we get result immediately. When we use subscribe then result is obtained asynchronously.

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

final HotelResult[] hotelResults = new HotelResult[1];
singleHotelResult.subscribe(hotelResult -> {
    hotelResults[0] = hotelResult;
});
// hotelResults[0] may be not initialized here yet
// println not show result yet (if operation for getting hotel info is long)
System.out.println(hotelResults[0]); 

For blocking case:

final HotelResult hotelResult = singleHotelResult.toBlocking().value();
// hotelResult has value here but program workflow will stuck here until API is being called.

toBlocking helps in the cases when you are using Observables in "normal" code where you need to have the result in place.

subscribe helps you for example in Android application when you can set some actions in subscribe like show result on the page, make button disabled etc.

Dmitry Gorkovets
  • 2,208
  • 1
  • 10
  • 19
  • I want to wait until the result is fetched. So even in case of subscribe I haven't mentioned any scheduler so that will also be a synchronous(in my opinion) call. For my use case I am going with blocking observable only. – Deepanshu Jan 15 '17 at 04:36