Rx 2 Android what is better Single or Observable f

2019-03-24 21:32发布

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

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-03-24 21:43

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 , 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)?
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-03-24 22:05

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.

查看更多
登录 后发表回答