I am trying to chain n
requests with Combine
.
Let's assume I have 50 users and for each of them I need to do a single request to get a users data. I know that with flatMap
you can pass one Publisher
result into the next. But does that work with loops as well?
That's my function to fetch a user:
func fetchUser(for id: Int) -> AnyPublisher<User, Error> {
let url = "https://user.com/api/user/\(id)"
return URLSession.shared.dataTaskPublisher(for: url)
.mapError { $0 as Error }
.map { $0.data }
.decode(type: User.self, decoder: JSONDecoder())
.eraseToAnyPublisher()
}
So basically I need another function, which loops this over this fetchUser
and returns all users in one result array. The requests should not all run at the same time, but rather start one after the previous one has finished.