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(); }
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.
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.
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.
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.
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)?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With