Subject
- Subject can be thought of as a bridge or proxy, and in some ReactiveX implementations, such as RxJava, it acts as both an Observer and an Observable. Because it is an Observer, it can subscribe to one or more Observables; Since it is an Observable, it can forward data it receives and transmit new data
- Subject is an abstract class and cannot be instantiated by new, so Subject has four implementation classes, respectively
-
- AsyncSubject Copy the code
-
- BehaviorSubject Copy the code
-
- PublishSubject Copy the code
-
- ReplaySubject Copy the code
AsyncSubject
The Observer receives the last data before the AsyncSubject’s ‘onComplete()’. If the AsyncSubject terminates due to an exception, the AsyncSubject does not release any data, but passes an exception notification to the Observer
BehaviorSubject
The Observer receives the last BehaviorSubject data before the BehaviorSubject was subscribed to, and then receives any other data that is sent. If the BehaviorSubject didn’t send any data before being subscribed to, it sends a default data.
(Note the difference with AsyncSubject, which manually calls onCompleted() and its Observer receives the last data sent before onCompleted() and no more data after that. The BehaviorSubject doesn’t need to manually call onCompleted(). Its Observer receives the last data that the BehaviorSubject sent before it was subscribed. The bounds of the BehaviorSubject are different, and the BehaviorSubject continues to receive data after that.
PublishSubject
PublishSubject is relatively easy to understand, and its Observer only receives data sent after the PublishSubject has been subscribed
ReplaySubject
ReplaySubject emits all data to observers regardless of when they subscribed. There are other versions of ReplaySubject that discard old data when reslowed down to a certain size or after a period of time.