1- Subject

An RxJS Subject is a special type of Observable that allows values to be multicasted to many Observers. While plain Observables are unicast (each subscribed Observer owns an independent execution of the Observable), Subjects are multicast.

PS: A Subject is like an Observable, but can multicast to many Observers. Subjects are like EventEmitters: they maintain a registry of many listeners.

In the example below, we have two Observers attached to a Subject, and we feed some values to the Subject:

import { Subject } from 'rxjs';

const subject = new Subject<number>();

subject.subscribe({
  next: (v) => console.log(`observerA: ${v}`)
});
subject.subscribe({
  next: (v) => console.log(`observerB: ${v}`)
});

subject.next(1);
subject.next(2);

// Logs:
// observerA: 1
// observerB: 1
// observerA: 2
// observerB: 2

2- Observable

Observable is a new way of handling asynchronous requests, just like Promises or callbacks. Concerning push and pull models, Observables is a push collection of multiple values.

Observable pass four stages during their lifecycle: creation, subscription, execution, and destruction.

There are many ways to create Observables, but the most common is using new Observable or Observable.create() methods. Let’s take a look at the code below.

import { Observable } from 'rxjs';
const myObservable = new Observable(observer => {
  setTimeout(() => {
    observer.next('Hello world!');
  }, 2000);
});

We have created a new Observable in this code example and assigned it to the myObservable constant. This Observable will emit the string Hello world! every two seconds to a subscriber.

Observable class constructor takes a function as a parameter, and that function has an observer object inside.

To make our Observable working, we have to subscribe to it, using .subscribe() method. We can compare subscribing Observable, to calling the function.

const observer = {
  next: value => console.log('Observer got the next value:' + value),
  error: error => console.log('Observer got an erro:r' + error),
  complete:() => console.log('Observer got a complete notification'),
};
myObservable.subscribe(observer);


// Result
Observer got the next value: Hello world!

Conclusion

subject: multicast & you can send to it and receive from it. (we can generate new data anytime, with subject.next() )

Observable: Unicast & you can receive from it only.

In another words, In subject you can subscribe to it and you can use it to broadcast to other subscribers any time and anywhere in code.

whilst, in observable you can subscribe to it only (you can’t use it to broadcast data after it have been initialized). The only place you can broadcast data from observable is inside its constructor.

By Shabazz

Software Engineer, MCSD, Web developer & Angular specialist

Leave a Reply

Your email address will not be published. Required fields are marked *