Search code examples
rx-javareactivex

When should I use blockingGet?


I am using RxJava a lot for work and seen some examples of calling a method which returns an Observable or Single and then calling blockingGet on it to use the results in a different . I was thinking this might be a misuse of the library and the concept but I might be wrong. I will give a small example:

   public Observable<String> getStrings(){
     // return sg
   }

   public Observable<String> getNames(){
     // return names
   }

   public Observable<String> filterNamesInStrings() {
     List<String> names = getNames().toList().blockingGet();

     return getStrings().filter(str -> /*is str in names list*/)
   }   

The filterNamesInStrings could also be solved by:

   getNames()
    .toList()
    .flatMapObservable(names-> 
       getStrings().filter(str -> /*is str in names list*/)

My intuition is that the second solution is better, but the only reason I have is that I feel with using blockingGet we kind of break the chain of observables, lose the laziness (I'm not sure tho how lazy Rx is) but I did not find anything to prove my points also nothing to further explain that the second is better. Also if I am right I don't see any other use case for blocking get than quick testing, is that true?

My questions:

  • Is my question a valid one or the difference is negligible between the implementations?
  • Is any of the solutions better/more true to the library than the other, if so why and is there a valid reason to use blockingGet then?
  • (Optional: Could you recommend me a good book on understanding the depths of ReactiveX, so I get explanations for questions like this and also a "good practices" list/book would be handy)

Solution

  • Is my question a valid one or the difference is negligible between the implementations?

    blockingGet blocks the current thread, so you almost certainly don't want to call it outside of tests. The second example is the right approach.

    Is any of the solutions better/more true to the library than the other, if so why and is there a valid reason to use blockingGet then?

    Tests mainly. Or rarely, when working with fully synchronous code where blocking never actually happens.

    understanding the depths of ReactiveX

    There is no book for this depth. All books about RxJava are fine to read.