Integrate Combine Into an App

Aug 5 2021 · Swift 5.4, macOS 11.3, Xcode 12.5

Part 1: Define a View Model

03. Create Data Publishers

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 02. Use @Published to Publish State Next episode: 04. Use Publishers in the ViewModel

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Before we can use publishers in our view model, we have to define them first. We’ll need to use them in our production and test code, so some overarching protocols will work best here.

public protocol JokeServiceDataPublisher {
  func publisher() -> AnyPublisher<Data, URLError>
}
public protocol TranslationServiceDataPublisher {
  func publisher(for joke: Joke, to languageCode: String)
    -> AnyPublisher<Data, URLError>
}
extension TranslationService: TranslationServiceDataPublisher {
  public func publisher(for joke: Joke, to languageCode: String)
    -> AnyPublisher<Data, URLError> {
    URLSession.shared.dataTaskPublisher(
      for: url(for: joke, languageCode: languageCode)
    )
    .map(\.data)
    .eraseToAnyPublisher()
  }
}
extension JokesService: JokeServiceDataPublisher {
  public func publisher() -> AnyPublisher<Data, URLError> {
    URLSession.shared
      .dataTaskPublisher(for: url)
      .map(\.data)
      .eraseToAnyPublisher()
  }
}
func publisher() -> AnyPublisher<Data, URLError> {
  // 1
  let publisher = CurrentValueSubject<Data, URLError>(data)
  
  // 2
  if let error = error {
    publisher.send(completion: .failure(error))
  }
  
  // 3
  return publisher.eraseToAnyPublisher()
}
func publisher(for joke: Joke, to languageCode: String) -> AnyPublisher<Data, URLError> {
  // 1
  let publisher = CurrentValueSubject<Data, URLError>(data)
  
  // 2
  if let error = error {
    DispatchQueue.global().asyncAfter(deadline: .now() + 0.1) {
      publisher.send(completion: .failure(error))
    }
  }
  
  // 3
  return publisher.eraseToAnyPublisher()
}