NetworkManager類具有用于從 Internet 獲取資料的fetchData通用函式。
class NetworkManager {
func fetchData<T: Decodable>(url: URL) -> AnyPublisher<T, ErrorType> {
URLSession
.shared
.dataTaskPublisher(for: url)
.tryMap { data, _ in
return try JSONDecoder().decode(T.self, from: data)
}
.mapError { error -> ErrorType in
switch error {
case let urlError as URLError:
switch urlError.code {
case .notConnectedToInternet, .networkConnectionLost, .timedOut:
return .noInternetConnection
case .cannotDecodeRawData, .cannotDecodeContentData:
return .empty
default:
return .general
}
default:
return .general
}
}
.eraseToAnyPublisher()
}
}
在HomeRepositoryImpl類中,我嘗試使用AnyPublisher<[CountryDayOneResponse], ErrorType>回傳值從特定 url 獲取資料。我想對回應的陣列進行排序,所以我在NetworkManager上使用了flatMap ,如下所示:
func getCountryStats(for countryName: String) -> AnyPublisher<[CountryDayOneResponse], ErrorType> {
let url = RestEndpoints.countryStats(countryName: countryName).endpoint()
return NetworkManager().fetchData(url: url)
.flatMap { result -> AnyPublisher<[CountryDayOneResponse], ErrorType> in
switch result {
case .success(var response):
let filteredCountry = Array(response.sorted(by: {$0.date > $1.date}))
response = filteredCountry
return response
case .failure(let error):
return error
}
}
.eraseToAnyPublisher()
}
但是我在當前背景關系錯誤中無法推斷閉包引數“結果”的型別。
uj5u.com熱心網友回復:
從我在你的代碼中看到的......你還沒有告訴它是什么result。即使以人類的身份閱讀它,我也無法判斷它應該是什么。
您的fetchData函式回傳一個AnyPublisher泛型型別T。
您的getCountryStats函式將該泛型型別T帶入flatMap函式并回傳AnyPublishertype [CountryDayOneResponse]。
但是你從來沒有告訴它是什么T。你甚至不告訴它是什么result。只有flatMap函式的輸出。
result預期的型別是什么?
評論后編輯。
如果你想要你的result,[CountryOneDayResponse]那么這段代碼就可以了......
func getCountryStats(for countryName: String) -> AnyPublisher<[CountryDayOneResponse], ErrorType> {
let url = RestEndpoints.countryStats(countryName: countryName).endpoint()
let publisher: AnyPublisher<[CountryDayOneResponse], ErrorType> = NetworkManager().fetchData(url: url)
return publisher
.flatMap{ Just(Array($0.sorted(by: {$0.date > $1.date}))) }
.eraseToAnyPublisher()
}
您不需要像在 中那樣打開結果,flatMap因為flatMap只有在發布者回傳非錯誤時才會輸入。所以你可以把 的輸入flatMap作為發布者的成功型別[CountryOneDayResponse]。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/446951.html
