In Combine, most of the time AnyPublisher
is used.
I was wanting to know how to create a publisher from a function that returned a Future for example:
func getAccount(id: Int) -> Future<Account, Error> {
Return Future<Account, Error> { promise in
promise(.success(repo.getAccount(id)))
}
}
I wanted to then return this value as a publisher like this:
func currentUser() -> AnyPublisher<Account, Error> {}
What I learned was that Future
is a type of Publisher
. Itβs actually one of a few concrete implementations of Publisher available in Combine.
With this new knowledge I was then able to write something like this:
func currentUser() -> AnyPublisher<Account, Error> {
getAccount(id: self.currentUserId)
.eraseToAnyPublisher()
}
And just like that I was able to create a publisher from a future.