Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rx 2 Android what is better Single or Observable for api calls?

Tags:

when we use retrofit2 for doing API rest calls with Rx, What is the best approach to use, Single or Observable?

public interface ApiService{  Single<Data> getDataFromServer();  Observable<Data> getDataFromServer(); } 
like image 863
Jose M Lechon Avatar asked Feb 01 '17 14:02

Jose M Lechon


People also ask

What is the difference between single and Observable in RxJava?

Observable: emit a stream elements (endlessly) Flowable: emit a stream of elements (endlessly, with backpressure) Single: emits exactly one element. Maybe: emits zero or one elements.

What is the advantage of RxJava in Android?

RxJava is a Java library that enables Functional Reactive Programming in Android development. It raises the level of abstraction around threading in order to simplify the implementation of complex concurrent behavior.

Why is RxJava dying?

All in all, in my opinion, RxJava in Android was a fiasco. It consumed enormous amount of community effort and attention, contaminated many codebases, didn't bring any value and, as of today, I can say that it pretty much died.

When should I use RxJava?

RxJava provides a standard workflow that is used to manage all data and events across the application like Create an Observable> Give the Observable some data to emit> Create an Observer> Subscribe the Observer to the Observable. RxJava is becoming more and more popular particularly for Android developers.


1 Answers

I'd suggest using a Single as it is more accurate representation of the data flow: you make a request to the server and the you get either one emission of data OR an error:

Single:     onSubscribe (onSuccess | onError)? 

For an Observable you could theoretically get several emissions of data AND an error

Observable: onSubscribe onNext? (onCompleted | onError)? 

However, if you are using rx-java2, I'd suggest using a Maybe instead of Single. The difference between those two is that Maybe handles also the case when you get the response from server but it contains no body.

Maybe:      onSubscribe (onSuccess | onCompleted | onError)? 
like image 129
Lamorak Avatar answered Oct 14 '22 00:10

Lamorak