What are the differences between observable and subject in rxSwift

advertisements

What are the differences between observable and subject. When I define a observable type variable. It can emit onNext,onComplete,onDispose. However subject can do the same. When should I use observable and in what case should I use subject?


In order to understand the difference between them, we should mention that Observable is:

In ReactiveX an observer subscribes to an Observable. Then that observer reacts to whatever item or sequence of items the Observable emits. This pattern facilitates concurrent operations because it does not need to block while waiting for the Observable to emit objects, but instead it creates a sentry in the form of an observer that stands ready to react appropriately at whatever future time the Observable does so.

In other words, observable is data producer (responsible for posting notifications to be observed).

Actually, Subject is a special type of Observables (you still can subscribe to messages like any other observable):

A Subject is a sort of bridge or proxy that is available in some implementations of ReactiveX that acts both as an observer and as an Observable. Because it is an observer, it can subscribe to one or more Observables, and because it is an Observable, it can pass through the items it observes by reemitting them, and it can also emit new items.

but the thing is subject is a representation -as mentioned in the documentation- of both observable and observer, which means that subject might be data producer (responsible for posting notifications to be observed or data consumer (responsible for receiving notifications).


Code snippets: I would suggest to check RxSwift For Dummies