【发布时间】:2018-06-23 08:33:50
【问题描述】:
我想合并两个 API 请求的结果。最初我让它们返回 Observable,但为了正确执行,我猜响应应该是 Single。
这是我最初的改造接口:
interface RemoteGeocodingService {
@GET("json")
fun requestCityAddressByName(
@Query("address") address: String
): Observable<LocationResponse>
}
interface RemoteWeatherService {
@GET("{latitude},{longitude}")
fun requestWeatherForCity(
@Path("latitude") latitude: String,
@Path("longitude") longitude: String
): Observable<WeatherResponse>
}
我像这样使用 lambda 组合它们的结果:
override fun getWeather(cityName: String): Observable<WeatherDetailsDTO>? {
return remoteWeatherDataSource.requestCityAddressByName(cityName)
.flatMap({ responseFromServiceA -> remoteWeatherDataSource.requestWeatherForCity(responseFromServiceA.results[0].geometry.location.lat.toString(), responseFromServiceA.results[0].geometry.location.lng.toString()) },
{ responseFromServiceA, responseFromServiceB ->
TransformersDTO.transformToWeatherDetailsDTO(responseFromServiceA.results[0].formatted_address, responseFromServiceB)
})
.retry()
}
但是,当我将每个 API 接口方法的请求结果更改为使用 Single 而不是 Observable 时,我无法执行此操作 - 我在 Android Studio IDE 编辑器中出现错误。这是我尝试过的:
override fun getWeather(cityName: String): Single<WeatherDetailsDTO> {
return remoteWeatherDataSource.requestCityAddressByName(cityName)
.flatMap({ responseFromServiceA: LocationResponse -> remoteWeatherDataSource.requestWeatherForCity(responseFromServiceA.results[0].geometry.location.lat.toString(), responseFromServiceA.results[0].geometry.location.lng.toString()) },
{ responseFromServiceA: LocationResponse, responseFromServiceB: WeatherResponse ->
TransformersDTO.transformToWeatherDetailsDTO(responseFromServiceA.results[0].formatted_address, responseFromServiceB)
})
.retry()
IDE 将 .flatMap 运算符标记为错误并显示:
以下函数都不能使用提供的参数调用。 flatMap(((t: LocationResponse) → SingleSource!)!) 无法推断出 R 的有趣 flatMap(mapper: ((t: LocationResponse) → SingleSource!)!): Single!在 io.reactivex.Single 中定义 flatMap(Function!>!) 其中 R 无法推断出有趣的 flatMap(mapper: Function!>!): Single!在 io.reactivex.Single 中定义
如何解决?
【问题讨论】:
-
没有
Single.flatMap(Function, BiFunction)方法。
标签: lambda functional-programming kotlin retrofit2 rx-java2