Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return custom exceptions in case of failure with RxJava + Retrofit

I have a repository class that must return this: Observable<List<SomeObject>, I do this:

 @Override
    public Observable<List<SomeObject>> getAllById(Long id) {
        if (!AndroidUtils.isNetworkAvailable(mContext))
            return Observable.error(new NoNetworkConnectionException());

        return mRestService.get(id);
    }

This approach works normally, the problem is I want to return custom exceptions in case of failures, but I don't know the best way to do this with rxjava.

So far, the only solution that works is something like that:

@Override
public Observable<List<SomeObject>> getAllById(Long id) {
    if (!AndroidUtils.isNetworkAvailable(mContext))
        return Observable.error(new NoNetworkConnectionException());

    return Observable.create(subscriber -> {
        mRestService.get(id).subscribe(new Observer<List<SomeObject>>() {
            @Override
            public void onCompleted() {
                subscriber.onCompleted();
            }

            @Override
            public void onError(Throwable e) {
                if (e instanceof HttpException  && ((HttpException) e).code() == 401)
                    subscriber.onError(new UnathorizedException());
                else
                    subscriber.onError(e);
            }

            @Override
            public void onNext(List<SomeObject> objects) {
                subscriber.onNext(objects);
            }
        });
    });
}

I know that is not a good thing to use Observable.create, but I can't figure out another way to do this.

RestService is this:

public interface RestService {

    @GET("objects/{id}")
    Observable<List<SomeObject>> get(@Path("id") Long id);
}

If anyone knows a better approach, please tell me.

Thanks!

like image 681
Luiz Avatar asked Aug 06 '16 23:08

Luiz


1 Answers

You can use the operator onErrorResumeNext to map your exception to another one.

mRestService.get(id)
            .onErrorResumeNext(e -> {
                if (e instanceof HttpException  && ((HttpException) e).code() == 401)
                    return Observable.error(new UnathorizedException());
                else
                    return Observable.error(e);
            })
            .subscribe();
like image 95
dwursteisen Avatar answered Oct 14 '22 05:10

dwursteisen