英文:
Unable to convert AnyPublisher to Another AnyPublisher
问题
以下是您提供的代码的中文翻译部分:
我正在尝试从AnyPublisher中获取一些模型,并使用该模型从另一个发布者获取数组。以下是我的代码:
public func getAllMyAppointments() -> AnyPublisher<[TelehealthMyAppointmentsListEntity]?, Error> {
telehealthMyAppointmentsAPIAccessTokenUseCase.getAccessToken().map { tokenDetails in
provider.getAllMyAppointments(with: tokenDetails)
}
.eraseToAnyPublisher()
}
但我得到了以下错误:
> 无法将类型为'AnyPublisher<[TelehealthMyAppointmentsListEntity]?, any Error>'的值转换为闭包结果类型'[TelehealthMyAppointmentsListEntity]?'
以下是我的方法签名:
func getAccessToken() -> (AnyPublisher<MyAppointmentsAPIAccessTokenDetails, Error>)
func getAllMyAppointments(with accessInformation: MyAppointmentsAPIAccessTokenDetails) -> AnyPublisher<[TelehealthMyAppointmentsListEntity]?, Error>
请注意,我只翻译了您提供的代码部分,没有包括其他内容。
英文:
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>
答案1
得分: 2
你在这里使用了 map
,但实际上应该使用 flatMap
。
对于一个类型为 AnyPublisher<T, Error>
的对象,使用 map
的目的是将其从 T
转换为 U
,得到一个 AnyPublisher<U, Error>
。
但是你想要的是使用一个 (T) -> AnyPublisher<U, Error>
来执行相同的操作,这正是 flatMap
的用途:
public func getAllMyAppointments() -> AnyPublisher<[TelehealthMyAppointmentsListEntity]?, Error> {
telehealthMyAppointmentsAPIAccessTokenUseCase.getAccessToken().flatMap { tokenDetails in
provider.getAllMyAppointments(with: tokenDetails)
}
.eraseToAnyPublisher()
}
英文:
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()
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论