Integrate Combine Into an App

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

Part 1: Define a View Model

04. Use Publishers in the ViewModel

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: 03. Create Data Publishers Next episode: 05. Use @ObservedObject to Monitor State

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've reached locked video content where the transcript will be shown as obfuscated text.

In the last episode, we made our own custom publishers that, in the end, started with a publisher (in this case a dataTaskPublisher from URLSession), and we performed some operations on that publisher, the last of which was erasing the type signature to AnyPublisher. This takes advantage of the fact that Operators are both Publishers and Subscribers.

private let jokesService: JokeServiceDataPublisher
private let translationService: TranslationServiceDataPublisher
public init(jokesService: JokeServiceDataPublisher = JokesService(),
            translationService: TranslationServiceDataPublisher = TranslationService()) {
  self.jokesService = jokesService
  self.translationService = translationService
}
$joke
  .map { _ in false }
  .assign(to: \.fetching, on: self)
  .store(in: &subscriptions)
public func fetchJoke() {
  // 1
  fetching = true
  // 2
  jokeSubscriptions = []
  jokesService.publisher()
    .retry(1)
    .decode(type: Joke.self, decoder: Self.decoder)
    .replaceError(with: Joke.error)
    .receive(on: DispatchQueue.main)
    
    .handleEvents(receiveOutput: { [unowned self] in
      self.joke = $0
    })
    .filter { $0 != Joke.error }
    .flatMap { [unowned self] joke in
      self.fetchTranslation(for: joke, to: "es")
    }
    .receive(on: DispatchQueue.main)
    .assign(to: \.joke, on: self)
    .store(in: &jokeSubscriptions)
}
func fetchTranslation(for joke: Joke, to languageCode: String)
  -> AnyPublisher<Joke, Never> {

  guard joke.languageCode != languageCode else {
    return Just(joke).eraseToAnyPublisher()
  }
  return translationService.publisher(for: joke, to: languageCode)
    .retry(1)
    .decode(type: TranslationResponse.self, decoder: Self.decoder)
    .compactMap { $0.translations.first }
    .map {
      Joke(id: joke.id,
           value: joke.value,
           categories: joke.categories,
           languageCode: languageCode,
           translationLanguageCode: languageCode,
           translatedValue: $0)
    }
    // 5
    .replaceError(with: Joke.error)
    .eraseToAnyPublisher()
}