connectable.js 855 B

1234567891011121314151617181920212223242526
  1. import { Subject } from '../Subject';
  2. import { Observable } from '../Observable';
  3. import { defer } from './defer';
  4. const DEFAULT_CONFIG = {
  5. connector: () => new Subject(),
  6. resetOnDisconnect: true,
  7. };
  8. export function connectable(source, config = DEFAULT_CONFIG) {
  9. let connection = null;
  10. const { connector, resetOnDisconnect = true } = config;
  11. let subject = connector();
  12. const result = new Observable((subscriber) => {
  13. return subject.subscribe(subscriber);
  14. });
  15. result.connect = () => {
  16. if (!connection || connection.closed) {
  17. connection = defer(() => source).subscribe(subject);
  18. if (resetOnDisconnect) {
  19. connection.add(() => (subject = connector()));
  20. }
  21. }
  22. return connection;
  23. };
  24. return result;
  25. }
  26. //# sourceMappingURL=connectable.js.map