【zZ】RxJava使用心得(一)

使用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

我英文不好,做不到流畅的翻译就将就看吧。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值