Search code examples
swiftcombine

Unable to convert AnyPublisher to Another AnyPublisher


I am trying to fetch some model from an AnyPublisher and using model get an array from another publisher. Following is my code:

public func getAllMyAppointments() -> AnyPublisher<[TelehealthMyAppointmentsListEntity]?, Error> {
    telehealthMyAppointmentsAPIAccessTokenUseCase.getAccessToken().map { tokenDetails in
        provider.getAllMyAppointments(with: tokenDetails)
    }
    .eraseToAnyPublisher()
}

But I am getting following error:

Cannot convert value of type 'AnyPublisher<[TelehealthMyAppointmentsListEntity]?, any Error>' to closure result type '[TelehealthMyAppointmentsListEntity]?'

Following is signature for my methods:

func getAccessToken() -> (AnyPublisher<MyAppointmentsAPIAccessTokenDetails, Error>)
func getAllMyAppointments(with accessInformation: MyAppointmentsAPIAccessTokenDetails) -> AnyPublisher<[TelehealthMyAppointmentsListEntity]?, Error>

Solution

  • You've used map when you mean flatMap.

    For an AnyPublisher<T>, the point of map is to use a (T) -> U to convert AnyPublisher<T> to AnyPublisher<U>.

    But what you want is to use a (T) -> AnyPublisher<U> to do the same thing. That is precisely flatMap:

    public func getAllMyAppointments() -> AnyPublisher<[TelehealthMyAppointmentsListEntity]?, Error> {
        telehealthMyAppointmentsAPIAccessTokenUseCase.getAccessToken().flatMap { tokenDetails in
            provider.getAllMyAppointments(with: tokenDetails)
        }
        .eraseToAnyPublisher()
    }