Skip to content

Instantly share code, notes, and snippets.

@banujan6
Last active September 5, 2021 08:00
Show Gist options
  • Save banujan6/ac431e09baef50b7e2bbff2c2f5a7055 to your computer and use it in GitHub Desktop.
Save banujan6/ac431e09baef50b7e2bbff2c2f5a7055 to your computer and use it in GitHub Desktop.
medium-rxjs-subject-vs-observable
import { Subject, Observable } from 'rxjs';
const observable = new Observable(subscriber => {
subscriber.next(Math.random()); // passing a random number
})
// Gives 2 different number. Because Observables are unicast and it will be execute separatly for each subscription.
observable.subscribe(data => {
console.log('subscription a :', data); //subscription a :0.2859800202682865
});
observable.subscribe(data => {
console.log('subscription b :', data); //subscription b :0.694302021731573
});
const subject = new Subject();
// Getting same data for both subscription, Because Subjects will be executed once and
// multicasting the data to multiple observers.
subject.subscribe(data => {
console.log('subscription a :', data); // subscription a : 0.91767565496093
});
subject.subscribe(data => {
console.log('subscription b :', data); // subscription b : 0.91767565496093
});
// passing from outsite. Yes we can do it for subject becuase it is bi-directional
subject.next(Math.random());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment