Intermediate Combine

Apr 13 2021 · Swift 5.3, macOS 11.1, Xcode 12.2

Part 1: Intermediate Combine

02. Sharing Resources

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: 01. Networking with Combine Next episode: 03. Managing Backpressure

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

In Combine, Publishers are usually structs, and therefore passed by value throughout your code, copying the publisher each time it passed around. Once it recieves a subscription, those individual publishers will do the only thing they can - start its work and deliver values.

example(of: "shared") {

let shared = URLSession.shared
  .dataTaskPublisher(for: rwUrl)
  .map(\.data)
  .print("shared")
  .share()
print("subscribing first")

shared.sink(
  receiveCompletion: { _ in },
  receiveValue: { print("subscription1 received: '\($0)'") }
)
.store(in: &subscriptions)
print("subscribing second")

var subscription2 = shared.sink(
  receiveCompletion: { _ in },
  receiveValue: { print("subscription2 received: '\($0)'") }
)
.store(in: &subscriptions)
var subscription2: AnyCancellable? = nil

DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
  print("subscribing second")

  subscription2 = shared.sink(
    receiveCompletion: { print("subscription2 completion \($0)") },
    receiveValue: { print("subscription2 received: '\($0)'") }
  )
}
// 1
example(of: "multicast") {
let subject = PassthroughSubject<Data, URLError>() // 2
// 2
let multicasted = URLSession.shared
  .dataTaskPublisher(for: rwUrl)
  .map(\.data)
  .print("shared")
  .multicast(subject: subject)
// 3
multicasted
  .sink(
    receiveCompletion: { _ in },
    receiveValue: { print("subscription1 received: '\($0)'") }
  )

multicasted
  .sink(
    receiveCompletion: { _ in },
    receiveValue: { print("subscription2 received: '\($0)'") }
  )
// 4
multicasted.connect()
// 5
subject.send(Data())