Skip to content

Instantly share code, notes, and snippets.

@mohsenoid
Last active February 4, 2018 17:51
Show Gist options
  • Save mohsenoid/73b733c6c12d42bb5ab3c977a40e3b7a to your computer and use it in GitHub Desktop.
Save mohsenoid/73b733c6c12d42bb5ab3c977a40e3b7a to your computer and use it in GitHub Desktop.
@Override
public void doSearch(boolean isConnected, String query, long timestamp) {
if (null != view) {
view.showProgress();
}
subscription = interactor.loadCharacter(query, Constants.PRIVATE_KEY, Constants.PUBLIC_KEY, timestamp)
// check if result code is OK
.map(charactersResponse -> {
if (Constants.CODE_OK == charactersResponse.getCode())
return charactersResponse;
else
throw Exceptions.propagate(new ApiResponseCodeException(charactersResponse.getCode(), charactersResponse.getStatus()));
})
// check if is there any result
.map(charactersResponse -> {
if (charactersResponse.getData().getCount() > 0)
return charactersResponse;
else
throw Exceptions.propagate(new NoSuchCharacterException());
})
// map CharacterResponse to CharacterModel
.map(Mapper::mapCharacterResponseToCharacter)
// cache data on database
.map(character -> {
try {
databaseHelper.addCharacter(character);
} catch (SQLException e) {
throw Exceptions.propagate(e);
}
return character;
})
.observeOn(scheduler.mainThread())
.subscribe(character -> {
if (null != view) {
view.hideProgress();
view.showCharacter(character);
if (!isConnected)
view.showOfflineMessage();
}
},
// handle exceptions
throwable -> {
if (null != view) {
view.hideProgress();
}
if (isConnected) {
if (null != view) {
if (throwable instanceof ApiResponseCodeException)
view.showServiceError((ApiResponseCodeException) throwable);
else if (throwable instanceof NoSuchCharacterException)
view.showQueryNoResult();
else
view.showRetryMessage(throwable);
}
} else {
if (null != view) {
view.showOfflineMessage();
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment