Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single vs Observable in Java RX

Tags:

java

reactivex

In the new release, reactiveX introduced Single, as a variant of Observable http://reactivex.io/documentation/single.html

Which is nice to have since in my current use-case, I have multiple executions, and each of them only returns a single result. So it will make sense if I change from using Observable to Single.

But then as a part of my use-case, for those multiple execution above, I need to concat them into one Observable stream later on (to get results from all above executions).

So now my question is, what is more beneficial in term of performance?

  1. Using Observable for each execution, although I know that the execution will return only 1 result.

or

  1. Using the Single for each execution, and only convert them to Observable when I need to concat the streams later on?

Thank you.

like image 798
Xitrum Avatar asked Mar 30 '16 16:03

Xitrum


3 Answers

Single is meant to be used when you expect a single value response.
Observable on the other hand is to be used for a stream or vector values.
So in terms of Reactive Pattern it's enough to use Single in case you expect the only 1 result and don't want to manipulate data

like image 154
Leonid Ustenko Avatar answered Oct 12 '22 06:10

Leonid Ustenko


From my knowledge, if I am understanding your situation entirely, it would make sense to have the Singles handle the earlier mentioned, multi-execution statements and combine said Singles with one Observerable.

I can't find great documentation to do this for performance reasons, but I can explain logically why it is better practice to use a Single when it is possible (although you are getting in the weeds when it comes to major refactoring).

Answer: Consider a situation where we use an Observable similar to your case (we know its only going to return a single value). With a Single, we have the logic to immediately turn to the OnSuccess method after a value is emitted, whereas in Observables we need to verify that it was the last and then call OnComplete.

Perhaps another dev can weigh in, but the logic behind it seems to makes sense.

like image 25
Chad Van De Hey Avatar answered Oct 12 '22 06:10

Chad Van De Hey


There are some cases when its appropriate to have the Observable return a single value (or error) and then end. There's a great explanation for it here: http://angusmorton.com/rx-single/

like image 2
solidak Avatar answered Oct 12 '22 07:10

solidak