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

岁酱吖の 提交于 2019-12-04 16:25:49

问题


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();
}

回答1:


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)?



回答2:


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.



来源:https://stackoverflow.com/questions/41982370/rx-2-android-what-is-better-single-or-observable-for-api-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!