Reputation:
I'm using RxJava for my network calls and before each request I need to check the network. Currently for each request I'm doing like this.
checkNetwork()
.andThen(netWorkCall())
.subscribe(new DisposableSubscriber<String>() {
@Override
public void onNext(String s) {
Log.d(TAG, "onNext: " + s);
}
@Override
public void onError(Throwable t) {
Log.d(TAG, "onError: " + t.getMessage());
}
@Override
public void onComplete() {
Log.d(TAG, "onComplete: ");
}
});
}
private Completable checkNetwork() {
return NetworkUtils.isConnected() ? Completable.complete() : Completable.error(new Throwable("Network Error"));
}
private Flowable<String> netWorkCall() {
return Flowable.just("Api response");
}
Is this the recommended way or is there any better way than this? Thanks in advance!!
Upvotes: 0
Views: 965
Reputation: 8106
Usually you don't check the network before. Better try to send the call and catch the errors when the request failed.
In your Repository which query the network you can prevalidate for a connection and throw an exception if the network connection failed.
That means:
networkCall()
.subscribe(
success -> { ... },
error -> { doSomethingWhenErrorHappened() }
);
private Flowable<String> netWorkCall() {
return networkAvailable() ? Flowable.just(...) : Flowable.error(...);
}
Thats the way it goes.
You should consider using a Single
or Maybe
since a network request usually returns only data onec or an error. Flowable is designed for using a stream.
Upvotes: 1