Reputation: 2454
Running with retrofit
This is my interface:
@GET("solicitation/all")
Observable<SolicitationResponse> getAll(@Query("X-Authorization") String apiKey);
This is where I run it:
apiService.getAll(getResources().getString(R.string.api_key))
.subscribeOn(Schedulers.io())
.flatMapIterable(SolicitationResponse::getData)
.observeOn(AndroidSchedulers.mainThread())
.delay(5L, java.util.concurrent.TimeUnit.SECONDS) // THIS DOESN'T WORK LIKE I WANT IT TO..
.repeat()
.subscribe(s -> Log.e(TAG, "data: " + s.getName()));
1) How can I add a conditional to only run if we have internet connection?
This doesn't work:
if (NetworkUtils.isConnected()) {
//observable above here
}
Why? Because the conditional code doesn't run itself endlessly, which means it will only check if we have internet connection once, ergo, it will crash if we lose it.
Is there any way to add a conditional before running the getAll method?
2) I need to add an interval before or after the task, by inserting .delay
it will delay the subscription, which is not what I want or need. How can I accomplish it in this particular situation?
Upvotes: 1
Views: 1685
Reputation: 10267
here's a suggestion:
Observable.fromCallable(() -> NetworkUtils.isConnected())
.flatMap(isConnected -> {
if (isConnected) {
return apiService.getAll(getResources().getString(R.string.api_key))
.subscribeOn(Schedulers.io())
.flatMapIterable(SolicitationResponse::getData);
} else {
return Observable.empty();
}
})
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.immediate())
.repeatWhen(observable -> observable.delay(5, TimeUnit.SECONDS))
.subscribe(s -> Log.e(TAG, "data: " + s.getName()));
1) the most straightforward way is to add the network check to the stream and using flatMap() conditionally decide what to do further.
2) adding delay before can be done using delaySubscription()
with the desired value, but then the delay will happen also with the first time, so the second approach of adding delay at the end seems more appropriate here, and can be done using repeatWhen()
Upvotes: 1