| 1 |
import { innerFrom } from '../observable/innerFrom'; |
| 2 |
import { Subject } from '../Subject'; |
| 3 |
import { SafeSubscriber } from '../Subscriber'; |
| 4 |
import { Subscription } from '../Subscription'; |
| 5 |
import { MonoTypeOperatorFunction, SubjectLike, ObservableInput } from '../types'; |
| 6 |
import { operate } from '../util/lift'; |
| 7 |
|
| 8 |
export interface ShareConfig<T> { |
| 9 |
/** |
| 10 |
* The factory used to create the subject that will connect the source observable to |
| 11 |
* multicast consumers. |
| 12 |
*/ |
| 13 |
connector?: () => SubjectLike<T>; |
| 14 |
/** |
| 15 |
* If `true`, the resulting observable will reset internal state on error from source and return to a "cold" state. This |
| 16 |
* allows the resulting observable to be "retried" in the event of an error. |
| 17 |
* If `false`, when an error comes from the source it will push the error into the connecting subject, and the subject |
| 18 |
* will remain the connecting subject, meaning the resulting observable will not go "cold" again, and subsequent retries |
| 19 |
* or resubscriptions will resubscribe to that same subject. In all cases, RxJS subjects will emit the same error again, however |
| 20 |
* {@link ReplaySubject} will also push its buffered values before pushing the error. |
| 21 |
* It is also possible to pass a notifier factory returning an `ObservableInput` instead which grants more fine-grained |
| 22 |
* control over how and when the reset should happen. This allows behaviors like conditional or delayed resets. |
| 23 |
*/ |
| 24 |
resetOnError?: boolean | ((error: any) => ObservableInput<any>); |
| 25 |
/** |
| 26 |
* If `true`, the resulting observable will reset internal state on completion from source and return to a "cold" state. This |
| 27 |
* allows the resulting observable to be "repeated" after it is done. |
| 28 |
* If `false`, when the source completes, it will push the completion through the connecting subject, and the subject |
| 29 |
* will remain the connecting subject, meaning the resulting observable will not go "cold" again, and subsequent repeats |
| 30 |
* or resubscriptions will resubscribe to that same subject. |
| 31 |
* It is also possible to pass a notifier factory returning an `ObservableInput` instead which grants more fine-grained |
| 32 |
* control over how and when the reset should happen. This allows behaviors like conditional or delayed resets. |
| 33 |
*/ |
| 34 |
resetOnComplete?: boolean | (() => ObservableInput<any>); |
| 35 |
/** |
| 36 |
* If `true`, when the number of subscribers to the resulting observable reaches zero due to those subscribers unsubscribing, the |
| 37 |
* internal state will be reset and the resulting observable will return to a "cold" state. This means that the next |
| 38 |
* time the resulting observable is subscribed to, a new subject will be created and the source will be subscribed to |
| 39 |
* again. |
| 40 |
* If `false`, when the number of subscribers to the resulting observable reaches zero due to unsubscription, the subject |
| 41 |
* will remain connected to the source, and new subscriptions to the result will be connected through that same subject. |
| 42 |
* It is also possible to pass a notifier factory returning an `ObservableInput` instead which grants more fine-grained |
| 43 |
* control over how and when the reset should happen. This allows behaviors like conditional or delayed resets. |
| 44 |
*/ |
| 45 |
resetOnRefCountZero?: boolean | (() => ObservableInput<any>); |
| 46 |
} |
| 47 |
|
| 48 |
export function share<T>(): MonoTypeOperatorFunction<T>; |
| 49 |
|
| 50 |
export function share<T>(options: ShareConfig<T>): MonoTypeOperatorFunction<T>; |
| 51 |
|
| 52 |
/** |
| 53 |
* Returns a new Observable that multicasts (shares) the original Observable. As long as there is at least one |
| 54 |
* Subscriber this Observable will be subscribed and emitting data. When all subscribers have unsubscribed it will |
| 55 |
* unsubscribe from the source Observable. Because the Observable is multicasting it makes the stream `hot`. |
| 56 |
* This is an alias for `multicast(() => new Subject()), refCount()`. |
| 57 |
* |
| 58 |
* The subscription to the underlying source Observable can be reset (unsubscribe and resubscribe for new subscribers), |
| 59 |
* if the subscriber count to the shared observable drops to 0, or if the source Observable errors or completes. It is |
| 60 |
* possible to use notifier factories for the resets to allow for behaviors like conditional or delayed resets. Please |
| 61 |
* note that resetting on error or complete of the source Observable does not behave like a transparent retry or restart |
| 62 |
* of the source because the error or complete will be forwarded to all subscribers and their subscription will be |
| 63 |
* closed. Only new subscribers after a reset on error or complete happened will cause a fresh subscription to the |
| 64 |
* source. To achieve transparent retries or restarts pipe the source through appropriate operators before sharing. |
| 65 |
* |
| 66 |
*  |
| 67 |
* |
| 68 |
* ## Example |
| 69 |
* |
| 70 |
* Generate new multicast Observable from the `source` Observable value |
| 71 |
* |
| 72 |
* ```ts |
| 73 |
* import { interval, tap, map, take, share } from 'rxjs'; |
| 74 |
* |
| 75 |
* const source = interval(1000).pipe( |
| 76 |
* tap(x => console.log('Processing: ', x)), |
| 77 |
* map(x => x * x), |
| 78 |
* take(6), |
| 79 |
* share() |
| 80 |
* ); |
| 81 |
* |
| 82 |
* source.subscribe(x => console.log('subscription 1: ', x)); |
| 83 |
* source.subscribe(x => console.log('subscription 2: ', x)); |
| 84 |
* |
| 85 |
* // Logs: |
| 86 |
* // Processing: 0 |
| 87 |
* // subscription 1: 0 |
| 88 |
* // subscription 2: 0 |
| 89 |
* // Processing: 1 |
| 90 |
* // subscription 1: 1 |
| 91 |
* // subscription 2: 1 |
| 92 |
* // Processing: 2 |
| 93 |
* // subscription 1: 4 |
| 94 |
* // subscription 2: 4 |
| 95 |
* // Processing: 3 |
| 96 |
* // subscription 1: 9 |
| 97 |
* // subscription 2: 9 |
| 98 |
* // Processing: 4 |
| 99 |
* // subscription 1: 16 |
| 100 |
* // subscription 2: 16 |
| 101 |
* // Processing: 5 |
| 102 |
* // subscription 1: 25 |
| 103 |
* // subscription 2: 25 |
| 104 |
* ``` |
| 105 |
* |
| 106 |
* ## Example with notifier factory: Delayed reset |
| 107 |
* |
| 108 |
* ```ts |
| 109 |
* import { interval, take, share, timer } from 'rxjs'; |
| 110 |
* |
| 111 |
* const source = interval(1000).pipe( |
| 112 |
* take(3), |
| 113 |
* share({ |
| 114 |
* resetOnRefCountZero: () => timer(1000) |
| 115 |
* }) |
| 116 |
* ); |
| 117 |
* |
| 118 |
* const subscriptionOne = source.subscribe(x => console.log('subscription 1: ', x)); |
| 119 |
* setTimeout(() => subscriptionOne.unsubscribe(), 1300); |
| 120 |
* |
| 121 |
* setTimeout(() => source.subscribe(x => console.log('subscription 2: ', x)), 1700); |
| 122 |
* |
| 123 |
* setTimeout(() => source.subscribe(x => console.log('subscription 3: ', x)), 5000); |
| 124 |
* |
| 125 |
* // Logs: |
| 126 |
* // subscription 1: 0 |
| 127 |
* // (subscription 1 unsubscribes here) |
| 128 |
* // (subscription 2 subscribes here ~400ms later, source was not reset) |
| 129 |
* // subscription 2: 1 |
| 130 |
* // subscription 2: 2 |
| 131 |
* // (subscription 2 unsubscribes here) |
| 132 |
* // (subscription 3 subscribes here ~2000ms later, source did reset before) |
| 133 |
* // subscription 3: 0 |
| 134 |
* // subscription 3: 1 |
| 135 |
* // subscription 3: 2 |
| 136 |
* ``` |
| 137 |
* |
| 138 |
* @see {@link shareReplay} |
| 139 |
* |
| 140 |
* @return A function that returns an Observable that mirrors the source. |
| 141 |
*/ |
| 142 |
export function share<T>(options: ShareConfig<T> = {}): MonoTypeOperatorFunction<T> { |
| 143 |
const { connector = () => new Subject<T>(), resetOnError = true, resetOnComplete = true, resetOnRefCountZero = true } = options; |
| 144 |
// It's necessary to use a wrapper here, as the _operator_ must be |
| 145 |
// referentially transparent. Otherwise, it cannot be used in calls to the |
| 146 |
// static `pipe` function - to create a partial pipeline. |
| 147 |
// |
| 148 |
// The _operator function_ - the function returned by the _operator_ - will |
| 149 |
// not be referentially transparent - as it shares its source - but the |
| 150 |
// _operator function_ is called when the complete pipeline is composed via a |
| 151 |
// call to a source observable's `pipe` method - not when the static `pipe` |
| 152 |
// function is called. |
| 153 |
return (wrapperSource) => { |
| 154 |
let connection: SafeSubscriber<T> | undefined; |
| 155 |
let resetConnection: Subscription | undefined; |
| 156 |
let subject: SubjectLike<T> | undefined; |
| 157 |
let refCount = 0; |
| 158 |
let hasCompleted = false; |
| 159 |
let hasErrored = false; |
| 160 |
|
| 161 |
const cancelReset = () => { |
| 162 |
resetConnection?.unsubscribe(); |
| 163 |
resetConnection = undefined; |
| 164 |
}; |
| 165 |
// Used to reset the internal state to a "cold" |
| 166 |
// state, as though it had never been subscribed to. |
| 167 |
const reset = () => { |
| 168 |
cancelReset(); |
| 169 |
connection = subject = undefined; |
| 170 |
hasCompleted = hasErrored = false; |
| 171 |
}; |
| 172 |
const resetAndUnsubscribe = () => { |
| 173 |
// We need to capture the connection before |
| 174 |
// we reset (if we need to reset). |
| 175 |
const conn = connection; |
| 176 |
reset(); |
| 177 |
conn?.unsubscribe(); |
| 178 |
}; |
| 179 |
|
| 180 |
return operate<T, T>((source, subscriber) => { |
| 181 |
refCount++; |
| 182 |
if (!hasErrored && !hasCompleted) { |
| 183 |
cancelReset(); |
| 184 |
} |
| 185 |
|
| 186 |
// Create the subject if we don't have one yet. Grab a local reference to |
| 187 |
// it as well, which avoids non-null assertions when using it and, if we |
| 188 |
// connect to it now, then error/complete need a reference after it was |
| 189 |
// reset. |
| 190 |
const dest = (subject = subject ?? connector()); |
| 191 |
|
| 192 |
// Add the finalization directly to the subscriber - instead of returning it - |
| 193 |
// so that the handling of the subscriber's unsubscription will be wired |
| 194 |
// up _before_ the subscription to the source occurs. This is done so that |
| 195 |
// the assignment to the source connection's `closed` property will be seen |
| 196 |
// by synchronous firehose sources. |
| 197 |
subscriber.add(() => { |
| 198 |
refCount--; |
| 199 |
|
| 200 |
// If we're resetting on refCount === 0, and it's 0, we only want to do |
| 201 |
// that on "unsubscribe", really. Resetting on error or completion is a different |
| 202 |
// configuration. |
| 203 |
if (refCount === 0 && !hasErrored && !hasCompleted) { |
| 204 |
resetConnection = handleReset(resetAndUnsubscribe, resetOnRefCountZero); |
| 205 |
} |
| 206 |
}); |
| 207 |
|
| 208 |
// The following line adds the subscription to the subscriber passed. |
| 209 |
// Basically, `subscriber === dest.subscribe(subscriber)` is `true`. |
| 210 |
dest.subscribe(subscriber); |
| 211 |
|
| 212 |
if ( |
| 213 |
!connection && |
| 214 |
// Check this shareReplay is still activate - it can be reset to 0 |
| 215 |
// and be "unsubscribed" _before_ it actually subscribes. |
| 216 |
// If we were to subscribe then, it'd leak and get stuck. |
| 217 |
refCount > 0 |
| 218 |
) { |
| 219 |
// We need to create a subscriber here - rather than pass an observer and |
| 220 |
// assign the returned subscription to connection - because it's possible |
| 221 |
// for reentrant subscriptions to the shared observable to occur and in |
| 222 |
// those situations we want connection to be already-assigned so that we |
| 223 |
// don't create another connection to the source. |
| 224 |
connection = new SafeSubscriber({ |
| 225 |
next: (value) => dest.next(value), |
| 226 |
error: (err) => { |
| 227 |
hasErrored = true; |
| 228 |
cancelReset(); |
| 229 |
resetConnection = handleReset(reset, resetOnError, err); |
| 230 |
dest.error(err); |
| 231 |
}, |
| 232 |
complete: () => { |
| 233 |
hasCompleted = true; |
| 234 |
cancelReset(); |
| 235 |
resetConnection = handleReset(reset, resetOnComplete); |
| 236 |
dest.complete(); |
| 237 |
}, |
| 238 |
}); |
| 239 |
innerFrom(source).subscribe(connection); |
| 240 |
} |
| 241 |
})(wrapperSource); |
| 242 |
}; |
| 243 |
} |
| 244 |
|
| 245 |
function handleReset<T extends unknown[] = never[]>( |
| 246 |
reset: () => void, |
| 247 |
on: boolean | ((...args: T) => ObservableInput<any>), |
| 248 |
...args: T |
| 249 |
): Subscription | undefined { |
| 250 |
if (on === true) { |
| 251 |
reset(); |
| 252 |
return; |
| 253 |
} |
| 254 |
|
| 255 |
if (on === false) { |
| 256 |
return; |
| 257 |
} |
| 258 |
|
| 259 |
const onSubscriber = new SafeSubscriber({ |
| 260 |
next: () => { |
| 261 |
onSubscriber.unsubscribe(); |
| 262 |
reset(); |
| 263 |
}, |
| 264 |
}); |
| 265 |
|
| 266 |
return innerFrom(on(...args)).subscribe(onSubscriber); |
| 267 |
} |