Hi all,
assume my Android app has this amazing Retrofit API:
interface AmazingApi {
@POST("/login")
Single<LoginInfo> login(@Body LoginBody body);
@POST("/logout")
Completable logout(@Body LogoutBody body);
@GET("/cool/{things}")
Observable<String> things(@Path("things") String things);
@GET("/gazillion/cool/{things}")
Flowable<String> gazillionThings(@Path("things") String things);
}
Before executing any of the methods, I’d like to check if network is available. As I have multiple source types (Single, Completable, etc.) I’ve implemented the following helper methods:
private <T> Single<T> withNetworkCheck(@NonNull Single<T> continuation) {
if (isOnline(context)) {
return continuation.onErrorResumeNext(throwable -> {
return Single.error(asHttpThrowable(throwable));
});
}
final String err = context.getString(R.string.offline);
return Single.error(new Throwable(err));
}
private <T> Observable<T> withNetworkCheck(@NonNull Observable<T> continuation) {
// Same impl. as above, but Observable instead of Single.
}
private Completable withNetworkCheck(@NonNull Completable continuation) {
// Same impl. as above, but Completable instead of Single.
}
// etc.
This yields the following calls:
withNetworkCheck(api.login(body));
withNetworkCheck(api.logout(body));
withNetworkCheck(api.things("foo"));
which is alright, but I'm not too happy with the amount of duplication in the helper methods.
Being relatively unexperienced with RxJava, I’m sure there’s a better/more elegant way of doing the above. Any help/hints?
Thanks!