Skip to main content

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.

David

Hi I'm David – I'm a creator, entrepreneur, and engineer. I add value to people to help them live a better life.

Leave a Reply

Get On David's Mailing List →
Close