Reactive Programming in iOS with Combine

Feb 4 2021 · Swift 5.3, macOS 11.0, Xcode 12.2

Part 1: Getting Started

03. Subscriber Operators and Subjects

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. Publishers and Subscribers Next episode: 04. Challenge: Create a Blackjack Dealer

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.

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)