w3b3 / angular-demo

Demo application with purpose of showcasing Angular and modern web platform features
https://angular-pwa-repo.firebaseapp.com/
0 stars 0 forks source link

Try BehaviorSubject (or Subject ) instead of generic Observable #76

Open w3b3 opened 5 years ago

w3b3 commented 5 years ago

BehaviorSubject (or Subject ) stores observer details, runs the code only once and gives the result to all observers . https://stackoverflow.com/questions/39494058/behaviorsubject-vs-observable https://jsbin.com/qowulet/edit?js,console

let randomNumGenerator1 = Rx.Observable.create(observer => {
   observer.next(Math.random());
});
let observer1 = randomNumGenerator1.subscribe(num => console.log('observer 1: '+ num));
let observer2 = randomNumGenerator1.subscribe(num => console.log('observer 2: '+ num));
let observer3 = randomNumGenerator1.subscribe(num => console.log('observer 3: '+ num));

let randomNumGenerator2 = new Rx.BehaviorSubject(0);
randomNumGenerator2.next(Math.random());
let observer1Subject = randomNumGenerator2.subscribe(num=> console.log('observer subject 1: '+ num));
let observer2Subject = randomNumGenerator2.subscribe(num=> console.log('observer subject 2: '+ num));
let observer3Subject = randomNumGenerator2.subscribe(num=> console.log('observer subject 3: '+ num));