Rx 2 Android api调用的Single或Observable更好的是什么? [英] Rx 2 Android what is better Single or Observable for api calls?
问题描述
当我们使用Retrofit2通过Rx进行API剩余调用时,最好的使用方法是Single还是Observable?
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();
}
推荐答案
我建议使用 Single
,因为它可以更准确地表示数据流:您向服务器发出请求,然后您会发出一个数据 OR 或一个错误:
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)?
对于 Observable
,理论上您可以得到数个发射数据 AND 一个错误
For an Observable
you could theoretically get several emissions of data AND an error
Observable: onSubscribe onNext? (onCompleted | onError)?
但是,如果您使用的是rx-java2 ,我建议使用 也许
而不是 Single
.两者之间的区别在于,当您从服务器获取响应但它不包含任何正文时,也许
也会处理这种情况.
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)?
这篇关于Rx 2 Android api调用的Single或Observable更好的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!