Search code examples
iosswiftrx-swift

Combine two single responses RXSwift


I have two Single values that contain an array of the same object. I want to merge them and apply the map and return them as a Single. Is it possible?

So I have this:

func fetchTripList(type: TripType) -> Single<[Trip]> {
    let response: Single<APITripListResponse> = request(target: TripsAPI.fetchUpcomingTripList)
    return response.map { $0.toModel() }
}

And I need something like this:

func fetchTripList(type: TripType) -> Single<[Trip]> {
    let responseUpcoming: Single<APITripListResponse> = request(target: TripsAPI.fetchUpcomingTripList)
    let responsePast: Single<APITripListResponse> = request(target: TripsAPI.fetchPastTripList)
    //'Declare a Singe variable <[Trip]> called X merge both responseUpcoming and responsePast, apply to them map { $0.toModel() } and return it'

    return X
}

Many thanks for the help.


Solution

  • If think merge operator is exactly what you want, it will wait until you get data from both of your requests, and then it will merge them into one array, which you can modify with map. And after that you can convert it to the single.

    So it looks like that:

    Observable.merge(responseUpcoming.asObservable(), responsePast.asObservable()).map { $0.toModel() }.asSingle()