【发布时间】:2021-11-25 19:12:48
【问题描述】:
我有三个 API 调用,其中两个相互依赖。
我设置了以下端点:
interface WeatherApi {
@GET("/data/2.5/onecall")
fun getWeather(
@Query("lat") lat: Double,
@Query("lon") lon: Double,
@Query("exclude") exclude: String,
@Query("units") units: String,
@Query("appid") appKey: String
): Observable<WeatherModel>
@GET("/geo/1.0/direct")
fun getCoordinates(
@Query("q") cityName: String,
@Query("appid") appKey: String
): Observable<LocationModel>
@GET("geo/1.0/reverse")
fun getNameForLocation(
@Query("lat") lat: Double,
@Query("lon") lon: Double,
@Query("appid") appKey: String
): Observable<LocationModel>
}
和
interface PlacesApi {
@GET("/maps/api/place/findplacefromtext/json")
fun getPlaceId(
@Query("input") cityName: String,
@Query("inputtype") inputType: String,
@Query("fields") fields: String,
@Query("key") appKey: String
): Observable<PlacesModel>
}
我的存储库如下所示:
class WeatherRepository constructor(
private val weatherService: WeatherApi,
private val placesService: PlacesApi,
) {
fun getCoordinates(cityName: String, appKey: String) =
weatherService.getCoordinates(cityName, appKey)
fun getWeather(lat: Double, lon: Double, exclude: String, units: String, appKey: String) =
weatherService.getWeather(lat, lon, exclude, units, appKey)
fun getPlaceId(placeName: String, appKey:String) =
placesService.getPlaceId(placeName, "textquery", "photos", appKey)
}
现在我想在 ViewModel 中获取所有需要的数据(三个模型)。所以我应该有一些方法,其中我将依次执行所有三个请求,如下所示:
locationModel = weatherRepository.getCoordinates(city, BuildConfig.WEATHER_API_KEY)
weatherModel = weatherRepository.getWeather(locationModel[0].lat!!, locationModel[0].lon!!)
placesModel = weatherRepository.getPlaceId(weatherModel, BuildConfig.PLACES_API_KEY)
毕竟我需要创建新模型,其中包括所有获取的数据。比如:
val cityModel = CityModel(
locationModel,
weatherModel,
placesModel
)
有人知道如何在 Kotlin 中使用 RxJava 来做这样的事情吗?
【问题讨论】:
-
zipWith想到了stackoverflow.com/questions/30219877/…
标签: android kotlin mvvm retrofit rx-java