I have a problem with throwing custom exceptions when using Retrofit2 and RxJava2.
Retrofit Api definition
public interface BackendInterface {
@Headers({"......"})
@POST("international-services/")
Observable<BackendResponse> post(@Body BackendRequest request, @Header("sessionId") String sessionId);
}
Usage of Retrofit Api
@Override
public Observable<SomeBusinessObject> getSomething(@NonNull String sessionId, @NonNull SomeOtherBusinessObject something) {
BackendRequest br = createBackendRequest(something);
return backendInterface.post(br, sessionId).map(backendResponse -> {
if (backendResponse.getResult().getCode() != 0) {
return Observable.error(new ServiceException("my custom exception"));
}
SomeBusinessObject result = mapBusinessObject(br);
return result;
});
}
The problem is the following line
return Observerable.error(new ServiceException("my custom exception"));
Android Studio marks it as error and says "no instance(s) of type variable(y) T exist so that Observable conforms to SomeBusinessObject inference variable R has incompatible bounds: equality contraints: SomeBusinessObject lower bounds: Observable
The IDE's quick fix suggests to make my method "getSomething" return Observable.
I have no idea how to forward custom exceptions to the subscriber of my observable.
Your .map
is trying to return both SomeBusinessObject
as well as Observable<"SomeType">
. Since they don't have a common parent object it cannot resolve what Observable.error()
should return.
The solution it to use .flatmap
instead and replacing the return with return Observable.just(result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.