PublishSubject in action

We can continue to work with the same project that we set up earlier in the chapter. Just use multiline comments to comment out the earlier code to differentiate between outputs from the current sections and the previous ones.

A PublishSubject emits only new items to its subscriber, that is, it does not replay events. We will create a PublishSubject instance named pubSubject:

let pubSubject = PublishSubject<String>()

Note that the PublishSubject initializer is empty, but we need to declare a type that is String in our case. Next, we will subscribe to it and print each emitted event. Subject is empty at this point, so the subscription will not yield anything:

pubSubject.subscribe {        print($0)    }

We will now use the ...

Get Reactive Programming with Swift 4 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.