Reputation: 570
I am new In RX-JAVA, Now I am facing one problem I just want to repeat one method till certain condition is not true. I am using Retrofit for network call. I'll hit one Google Calendar API, from this API response I'll get one token if That token value is not empty or Non null than I need to use this token to call the same API with this token.
public void getGoogleCalenderEvents(String auth, String calenderId, String token) {
auth = AUTH_HEADER_PREFIX + auth;
String orderBy = "updated";
Pair<Calendar, Calendar> pair = getCalendarStartAndEndTime();
String finalAuth = auth;
mCalenderApiRequest.getAllEvent(auth, calenderId, pair.first, pair.second, orderBy)
.map(response -> {
FileLogUtils.d(TAG, "getGoogleCalenderEvents():: deleting the previous data and storing into DB: response:" + response);
EventsRepository.getInstance().deleteAllData();
EventsRepository.getInstance().insert(response.toString());
return response;
}).subscribe(response-> {
if (TextUtils.isEmpty(response.getToken)){
getGoogleCalenderEvents(finalAuth, calenderId,response.getToken());
} else {
// Nothing ToDo
}
}, ErrorHandler::logError);
}
Upvotes: 0
Views: 563
Reputation: 6988
In order to have a proper code I need to know the signature of mCalenderApiRequest.getAllEvent
. For the code below I'm assuming it returns a Single
:
mCalenderApiRequest.getAllEvent(auth, calenderId, pair.first, pair.second, orderBy)
// same as your original code but with doOnSuccess instead of flatMap
.doOnSuccess(response -> {
FileLogUtils.d(TAG, "getGoogleCalenderEvents():: deleting the previous data and storing into DB: response:" + response);
EventsRepository.getInstance().deleteAllData();
EventsRepository.getInstance().insert(response.toString());
})
// check if response has empty token and throw EmptyTokenException
.flatMap(response -> {
if (response.getToken().isEmpty()) {
return Single.error(new EmptyTokenException());
} else {
return Single.just(response);
}
})
// check if error thrown is EmptyTokenException and retry
.retryWhen(errors -> errors.flatMap(error -> {
if (error instanceof EmptyTokenException) {
// the value returned is irrelevant
return Flowable.just("retry me!");
}
// don't retry if error thrown is different than EmptyTokenException
return Flowable.error(error);
}
))
.subscribe(response -> {
// nothing to do
}, ErrorHandler::logError);
and create this auxiliary class:
class EmptyTokenException extends Exception {}
Upvotes: 1