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!
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With