Это будет очень хорошо работать с функцией или классом , я использую функцию для простоты.
def gatherdata(fighter_name):
api = 'https://mma.now.sh/?fighter={0}'.format(fighter_name)
r = requests.get(api)
data = r.json()
name = data['name']
nickname = data['nickname']
fullName = data['fullname']
record = data['record']
association = data['association']
age = data['age']
birthday = data['birthday']
hometown = data['hometown']
nationality = data['nationality']
location = data['location']
height = data['height']
height_cm = data['height_cm']
weight = data['weight']
weight_kg = data['weight_kg']
weight_class = data['weight_class']
college = data['college']
degree = data['degree']
summary = data['summary']
print(name)
#Get all Fighters from the csv into this list
fighters = []
for fighter_name in fighters:
gatherdata(fighter_name)
Используйте этот код
, генерируйте исключение NullPointerException из flatMap
и отлавливайте ошибку с помощью .onErrorReturn (throwable -> {// ваша работа здесь})
@Carson J .
Для наиболее читаемого кода определите функцию расширения следующим образом:
private fun <T> Single<Response<T>>.decorateWithErrorHandling(): Single<T> {
return this
.onErrorResumeNext { throwable ->
// Map network layer exceptions, e.g. IOException to your specific "domain level" exceptions
Single.error(mapNetworkErrorToSpecificThrowable(throwable))
}
.flatMap { response ->
if (response.isSuccessful) {
Single.just(response.body())
} else {
Single.error(convertToSpecificThrowable(response))
}
}
}
Используйте ее следующим образом:
apiCall1()
.composeWithErrorHandling().flatMap { result1 -> apiCall2(result1) }
.composeWithErrorHandling().flatMap { result2 -> apiCall3(result2) }
и т. Д.