0

I'm new to Swift Combine, so having a small issue

Im trying to call two api calls, and merge the results as the second API call depends on the result from the first call.

Here is the code

return self.gameRepository.fetchGames(forUser: user.id)
            .map { games -> AnyPublisher<[Game], ApiError> in
                let result = games.map { gameDto -> Game in
                    let location = self.venueRepository.fetch(by: gameDto.siteId)
                        .map { $0.mapToModel() }
                    let game = gameDto.mapToModel(location: location)
                    return game
                }

My error is on line 4 "let location" the compiler complains when I try and pass this through to line 5

game.mapToModel(location: location)

Cannot convert value of type 'AnyPublisher' to expected argument type Location

The fetch call signature from the repository looks like this

func fetch(by id: String) -> AnyPublisher<LocationDto, ApiError>

So it is correct, but the .map call I use on the result allows the

$0.mapToModel() 

to occur, so I have locationDto object that allows me to cast to my Domain model.

Any help on how I can call these two apis together would be much appreciated.

ngatirauks
  • 779
  • 8
  • 18
  • You are probably looking for either `flatMap` or `switchToLatest`. But you might also need to use `MergeMany`. – rob mayoff Mar 02 '20 at 01:17
  • There is a good topic that provides many approaches to solve tasks like yours [Combine framework serialize async operations](https://stackoverflow.com/questions/59743938/combine-framework-serialize-async-operations), it should be helpful. Of course I recommend my approach :^), but it does not important. – Asperi Mar 02 '20 at 07:38

1 Answers1

0

Instead of the first map operator, try to use flatMap and return from this .flatmap AnyPublisher with your model, that needs to be passed to another request. Pseudocode:

fetchGames -> AnyPublisher<[Game]> // First request
fetchGame(by id: String) -> AnyPublisher<LocationDto> // Second request that depends on model from first one

fetchGames.flatMap { fetchGame(by: $0.id) }
Dmitriy Lupych
  • 609
  • 7
  • 9