Search code examples
iosswiftrx-swiftrx-cocoa

Convert [Observable<T>] to Observable<[T]> in RxSwift


Here's my implementation.

I have favCitiesID = Observable<[Int]> that will be flatMap and map. Each city id will be used in API call that will return Observable<CityMappable>. I have reached to the point where I can get [Observable<CityMappable>] but I want to transform it into Observable<[CityMappable]> so I can bind it to tableview datasource.

let favCitiesID: Observable<[Int]> = Observable.of([0,1,2])

let observableCities = favCitiesID.flatMap { cityIds -> Observable<[CityMappable]> in
        return cityIds.map{ return self.apiManager.getCurrentWeatherData(for: $0)}
}

This is APIManager function definition

func getCurrentWeatherData(for cityID: Int)->Observable<CityMappable>

Solution

  • You can use combine to convert from [Observable<CityMappable>] to Observable<[CityMappable]>.

    Try this code

    let observableCities = favCitiesID.flatMap { cityIds -> Observable<[CityMappable]> in
        let obs = cityIds.map{ return self.apiManager.getCurrentWeatherData(for: $0)}
        return Observable.combineLatest(obs)
    }