Reactive Programming in iOS with Combine

Feb 4 2021 Swift 5.3, macOS 11.0, Xcode 12.2

Part 1: Getting Started

3. Subscriber Operators and Subjects

Lesson Complete

Play Next Lesson
Next
Save for later
About this episode

See course reviews

See forum comments
Cinema mode Mark as Complete Download course materials
Previous episode: 2. Publishers and Subscribers Next episode: 4. Challenge: Create a Blackjack Dealer

This video was last updated on Feb 4 2021

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.

Although you ignored them in the previous example, the sink operator actually provides two closures: one to handle receiving a completion event, and one to handle receiving values. Let’s jump back into some code to see that in action.

example(of: "Just") {
  let just = Just("Hello world!")

  just
    .sink(
      receiveCompletion: {
        print("Received completion", $0)
    },
      receiveValue: {
        print("Received value", $0)
    })
    .store(in: &subscriptions)
}
example(of: "assign(to:on:)") {
  class SomeObject {
    var value: String = "" {
      didSet {
        print(value)
      }
    }
  }

  let object = SomeObject()
}
["Hello", "world!"].publisher
  .assign(to: \.value, on: object)
  .store(in: &subscriptions)
——— Example of: assign(to:on:) ———
Hello
world!
example(of: "PassthroughSubject") {
  let subject = PassthroughSubject<String, Never>()

  subject
    .sink(receiveValue: { print($0) })
    .store(in: &subscriptions)
}
subject.send("Hello")
subject.send("World")
——— Example of: PassthroughSubject ———
Hello
World
subject.send(completion: .finished)
subject.send("Still there?")
——— Example of: PassthroughSubject ———
Hello
World
example(of: "CurrentValueSubject") {
let subject = CurrentValueSubject<Int, Never>(0)

subject
  .sink(receiveValue: { print($0) })
  .store(in: &subscriptions)
}
print(subject.value)

subject.send(1)
subject.send(2)

print(subject.value)

subject.send(completion: .finished)
——— Example of: CurrentValueSubject ———
0
0
1
2
2
.print()
——— Example of: CurrentValueSubject ———
receive subscription: (CurrentValueSubject)
request unlimited
receive value: (0)
0
0
receive value: (1)
1
receive value: (2)
2
2
receive finished
example(of: "Type erasure") {
  let subject = PassthroughSubject<Int, Never>()

  let publisher = subject.eraseToAnyPublisher()
}
publisher.send(0)
//  publisher.send(0)
publisher
  .sink(receiveValue: { print($0) })
  .store(in: &subscriptions)

subject.send(0)