Subjects act as both an observable and an observer. You saw earlier how they can receive events and also be subscribed to. In the above example, the subject received next events, and for each of them, it turned around and emitted it to its subscriber.
There are four subject types in RxSwift:
PublishSubject: Starts empty and only emits new elements to subscribers.BehaviorSubject: Starts with an initial value and replays it or the latest element to new subscribers.ReplaySubject: Initialized with a buffer size and will maintain a buffer of elements up to that size and replay it to new subscribers.AsyncSubject: Emits only the last next event in the sequence, and only when the subject receives a completed event. This is a seldom used kind of subject, and you won’t use it in this book. It’s listed here for the sake of completeness.RxSwift also provides a concept called Relays. RxSwift provides two of these, named PublishRelay and BehaviorRelay. These wrap their respective subjects, but only accept and relay next events. You cannot add a completed or error event onto relays at all, so they’re great for non-terminating sequences.
Note: Did you notice the additional import RxRelay in this chapter’s playground? Originally, relays were part of RxCocoa, RxSwift’s suite of reactive Cocoa extensions and utilities. However, relays are a general-use concept that are also useful in non-Cocoa development environments such as Linux and command line tools. So it was split into its own consumable module, which RxCocoa depends on.
Next, you’ll learn more about these subjects and relays and how to work with them, starting with publish subjects.
RxSwift: Reactive Programming with Swift, Chapter 3: Subjects