rxjsrx-swiftreactivexfrp

Confusion around understanding the difference between Observable and Subject in RX


After reading a large number of posts on stack overflow, I am still very confused about the difference between Observable and Subject in Rx.

Basically, most people point out that the key difference between the two is that "The Subject class inherits both Observable and Observer, in the sense that it is both an observer and an observable", and it can be demonstrated by the following code snippet:

var subject = new Rx.Subject();

var subscription = subject.subscribe(
function (x) { console.log('onNext: ' + x); },
function (e) { console.log('onError: ' + e.message); },
function () { console.log('onCompleted'); }
);

subject.onNext(1);
// => onNext: 1

subject.onNext(2);
// => onNext: 2

subject.onCompleted();
// => onCompleted

I understand that in the following part of the code, subject is being the role of an observable that can be subscribed to:

var subscription = subject.subscribe(
function (x) { console.log('onNext: ' + x); },
function (e) { console.log('onError: ' + e.message); },
function () { console.log('onCompleted'); }
);

What really confuses me is this part:

subject.onNext(1);
// => onNext: 1

subject.onNext(2);
// => onNext: 2

subject.onCompleted();
// => onCompleted

It looks like here it demonstrates that subject can be the role of an observer as well, but my understanding is that here subject is also feeding values/events (sending 1, 2 and complete event). So why is the subject considered the role of an observer in the code above?

Thanks a lot.


Solution

  • The subject is considered as taking the role of an observer in the referenced code precisely because onNext and onCompleted are being called on it. An Observer is defined as an object on which you can call onNext and onCompleted (as well as onError.)