Reactive Programming in iOS with Combine, Episode 20: Challenge: Advanced Combining | Kodeco, the new raywenderlich.com

In this hands-on challenge, build upon the last challenge to interleave multiple arrays of data together.


This is a companion discussion topic for the original entry at https://www.kodeco.com/5429795-reactive-programming-in-ios-with-combine/lessons/20

For anybody who might find it useful. I found two other variations of the zip operator that could be used to resolve this challenge. One allows accepting two publishers as parameters instead of one and the other accepts a transform closure allowing to remove the map operator from the solution.

Here’s how to use them:

example(of: "Original solution to the challenge") {
  let phoneNumbersPublisher = ["123-4567", "555-1212", "555-1111", "123-6789"].publisher
  let areaCodePublisher = ["410", "757", "800", "540"].publisher
  let phoneExtensionPublisher = ["EXT 901", "EXT 523", "EXT 137", "EXT 100"].publisher

  areaCodePublisher
    .zip(phoneNumbersPublisher)
    .map { $0 + "-" + $1 }
    .zip(phoneExtensionPublisher)
    .map { $0 + " " + $1 }
    .sink {
      print($0)
    }
    .store(in: &subscriptions)
}

example(of: "Example of zip with transform closure") {

  let phoneNumbersPublisher = ["123-4567", "555-1212", "555-1111", "123-6789"].publisher
  let areaCodePublisher = ["410", "757", "800", "540"].publisher
  let phoneExtensionPublisher = ["EXT 901", "EXT 523", "EXT 137", "EXT 100"].publisher

  phoneNumbersPublisher
    .zip(areaCodePublisher) { [$1, $0].joined(separator: "-") }
    .zip(phoneExtensionPublisher) { [$0, $1].joined(separator: " ") }
    .sink {
      print($0)
    }
    .store(in: &subscriptions)
}

example(of: "Solution with a single zip") {
  let phoneNumbersPublisher = ["123-4567", "555-1212", "555-1111", "123-6789"].publisher
  let areaCodePublisher = ["410", "757", "800", "540"].publisher
  let phoneExtensionPublisher = ["EXT 901", "EXT 523", "EXT 137", "EXT 100"].publisher

  areaCodePublisher
    .zip(phoneNumbersPublisher, phoneExtensionPublisher)
    .map { $0 + "-" + $1 + " " + $2 }
    .sink {
      print($0)
    }
    .store(in: &subscriptions)
}
1 Like