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();
}
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();
}
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)?
Difference between Observable
and Single
is rather semantic. When you are declaring something Single
you are saying that this observable is going to produce only one value, not series of values.
Using proper semantic types is the best way to document your API.