使用RxJava结合Retrofit进行网络数据的请求
网络请求:
/**
* e.g.
* https://api.github.com/user/1
*
* @param id id号
* @return
*/
@GET ("/user/{id}")
Observable<UserEntity> getUser(@Path ("id") long id);
返回的数据可能的是成功查询到id=1的用户,或者返回没有查询到。
成功:
{"login":"50","id":12736272,"avatar_url":"https://avatars.githubusercontent.com/u/12736272?v=3","gravatar_id":"","url":"https://api.github.com/users/50","html_url":"https://github.com/50","followers_url":"https://api.github.com/users/50/followers","following_url":"https://api.github.com/users/50/following{/other_user}","gists_url":"https://api.github.com/users/50/gists{/gist_id}","starred_url":"https://api.github.com/users/50/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/50/subscriptions","organizations_url":"https://api.github.com/users/50/orgs","repos_url":"https://api.github.com/users/50/repos","events_url":"https://api.github.com/users/50/events{/privacy}","received_events_url":"https://api.github.com/users/50/received_events","type":"User","site_admin":false,"name":null,"company":null,"blog":null,"location":null,"email":null,"hireable":null,"bio":null,"public_repos":0,"public_gists":0,"followers":0,"following":0,"created_at":"2015-06-03T18:53:22Z","updated_at":"2015-06-03T19:17:43Z"}
失败:
{"message":"Not Found","documentation_url":"https://developer.github.com/v3"}
问题来了 , 因为Retrofit可以自动填充POJO对象,但是对于没有返回正确数据的时候就会回调failure方法
像这样儿
ApiAction.getApiService().getUser(id, new Callback<UserEntity>() {
@Override
public void success(UserEntity userEntity, Response response) {
Uri uri = Uri.parse(userEntity.getAvatar_url());
mSDVImageView = (SimpleDraweeView) findViewById(R.id.sdv_image_view);
mSDVImageView.setImageURI(uri);
Timber.d("success id ----> " + id);
}
@Override
public void failure(RetrofitError error) {
id++;
Timber.d("failure id ----> " + id);
}
});
但是如果使用Rxjava出现这种情况呢?doOnError?
NO,因为这个是在Retrofit的层次出的错,所以doOnError方法将不会起效,我们需要使用其他的操作符
- onErrorResumeNext( ) — instructs an Observable to emit a sequence of items if it encounters an error
- onErrorReturn( ) — instructs an Observable to emit a particular item when it encounters an error
- onExceptionResumeNext( ) — instructs an Observable to continue emitting items after it encounters an exception (but not another variety of throwable)
- retry( ) — if a source Observable emits an error, resubscribe to it in the hopes that it will complete without error
- retryWhen( ) — if a source Observable emits an error, pass that error to another Observable to determine whether to resubscribe to the source
我英文不好,做不到流畅的翻译就将就看吧。