| 1 |
import { Connectable, ObservableInput, SubjectLike } from '../types'; |
| 2 |
import { Subject } from '../Subject'; |
| 3 |
import { Subscription } from '../Subscription'; |
| 4 |
import { Observable } from '../Observable'; |
| 5 |
import { defer } from './defer'; |
| 6 |
|
| 7 |
export interface ConnectableConfig<T> { |
| 8 |
/** |
| 9 |
* A factory function used to create the Subject through which the source |
| 10 |
* is multicast. By default this creates a {@link Subject}. |
| 11 |
*/ |
| 12 |
connector: () => SubjectLike<T>; |
| 13 |
/** |
| 14 |
* If true, the resulting observable will reset internal state upon disconnection |
| 15 |
* and return to a "cold" state. This allows the resulting observable to be |
| 16 |
* reconnected. |
| 17 |
* If false, upon disconnection, the connecting subject will remain the |
| 18 |
* connecting subject, meaning the resulting observable will not go "cold" again, |
| 19 |
* and subsequent repeats or resubscriptions will resubscribe to that same subject. |
| 20 |
*/ |
| 21 |
resetOnDisconnect?: boolean; |
| 22 |
} |
| 23 |
|
| 24 |
/** |
| 25 |
* The default configuration for `connectable`. |
| 26 |
*/ |
| 27 |
const DEFAULT_CONFIG: ConnectableConfig<unknown> = { |
| 28 |
connector: () => new Subject<unknown>(), |
| 29 |
resetOnDisconnect: true, |
| 30 |
}; |
| 31 |
|
| 32 |
/** |
| 33 |
* Creates an observable that multicasts once `connect()` is called on it. |
| 34 |
* |
| 35 |
* @param source The observable source to make connectable. |
| 36 |
* @param config The configuration object for `connectable`. |
| 37 |
* @returns A "connectable" observable, that has a `connect()` method, that you must call to |
| 38 |
* connect the source to all consumers through the subject provided as the connector. |
| 39 |
*/ |
| 40 |
export function connectable<T>(source: ObservableInput<T>, config: ConnectableConfig<T> = DEFAULT_CONFIG): Connectable<T> { |
| 41 |
// The subscription representing the connection. |
| 42 |
let connection: Subscription | null = null; |
| 43 |
const { connector, resetOnDisconnect = true } = config; |
| 44 |
let subject = connector(); |
| 45 |
|
| 46 |
const result: any = new Observable<T>((subscriber) => { |
| 47 |
return subject.subscribe(subscriber); |
| 48 |
}); |
| 49 |
|
| 50 |
// Define the `connect` function. This is what users must call |
| 51 |
// in order to "connect" the source to the subject that is |
| 52 |
// multicasting it. |
| 53 |
result.connect = () => { |
| 54 |
if (!connection || connection.closed) { |
| 55 |
connection = defer(() => source).subscribe(subject); |
| 56 |
if (resetOnDisconnect) { |
| 57 |
connection.add(() => (subject = connector())); |
| 58 |
} |
| 59 |
} |
| 60 |
return connection; |
| 61 |
}; |
| 62 |
|
| 63 |
return result; |
| 64 |
} |