utilities/makeHot.js

  1. import { Observable } from '../Observable';
  2. import { Subject } from '../Subject';
  3. /**
  4. * Makes an observable "hot" -- very useful for things like DOM event listeners
  5. * so that the events do not get bound numerous amounts of times
  6. *
  7. * @memberof utilities
  8. *
  9. * @param {Observable} cold$
  10. * @returns {Observable}
  11. */
  12. export const makeHot = (cold$) => {
  13. const subject = new Subject();
  14. let mainSub = cold$.subscribe(subject);
  15. let refs = 0;
  16. return new Observable((observer) => {
  17. refs++;
  18. // if the main subscription is complete we have to resubscribe to it
  19. if (mainSub.isComplete) {
  20. mainSub = cold$.subscribe(subject);
  21. }
  22. let sub = subject.subscribe(observer);
  23. return () => {
  24. refs--;
  25. if (refs === 0) mainSub.unsubscribe();
  26. sub.unsubscribe();
  27. };
  28. });
  29. };
  30. Observable.prototype.makeHot = function () {
  31. return makeHot(this);
  32. };