| 1 |
import { asyncScheduler } from '../scheduler/async'; |
| 2 |
import { MonoTypeOperatorFunction, SchedulerLike, OperatorFunction, ObservableInput, ObservedValueOf } from '../types'; |
| 3 |
import { isValidDate } from '../util/isDate'; |
| 4 |
import { Subscription } from '../Subscription'; |
| 5 |
import { operate } from '../util/lift'; |
| 6 |
import { Observable } from '../Observable'; |
| 7 |
import { innerFrom } from '../observable/innerFrom'; |
| 8 |
import { createErrorClass } from '../util/createErrorClass'; |
| 9 |
import { createOperatorSubscriber } from './OperatorSubscriber'; |
| 10 |
import { executeSchedule } from '../util/executeSchedule'; |
| 11 |
|
| 12 |
export interface TimeoutConfig<T, O extends ObservableInput<unknown> = ObservableInput<T>, M = unknown> { |
| 13 |
/** |
| 14 |
* The time allowed between values from the source before timeout is triggered. |
| 15 |
*/ |
| 16 |
each?: number; |
| 17 |
|
| 18 |
/** |
| 19 |
* The relative time as a `number` in milliseconds, or a specific time as a `Date` object, |
| 20 |
* by which the first value must arrive from the source before timeout is triggered. |
| 21 |
*/ |
| 22 |
first?: number | Date; |
| 23 |
|
| 24 |
/** |
| 25 |
* The scheduler to use with time-related operations within this operator. Defaults to {@link asyncScheduler} |
| 26 |
*/ |
| 27 |
scheduler?: SchedulerLike; |
| 28 |
|
| 29 |
/** |
| 30 |
* A factory used to create observable to switch to when timeout occurs. Provides |
| 31 |
* a {@link TimeoutInfo} about the source observable's emissions and what delay or |
| 32 |
* exact time triggered the timeout. |
| 33 |
*/ |
| 34 |
with?: (info: TimeoutInfo<T, M>) => O; |
| 35 |
|
| 36 |
/** |
| 37 |
* Optional additional metadata you can provide to code that handles |
| 38 |
* the timeout, will be provided through the {@link TimeoutError}. |
| 39 |
* This can be used to help identify the source of a timeout or pass along |
| 40 |
* other information related to the timeout. |
| 41 |
*/ |
| 42 |
meta?: M; |
| 43 |
} |
| 44 |
|
| 45 |
export interface TimeoutInfo<T, M = unknown> { |
| 46 |
/** Optional metadata that was provided to the timeout configuration. */ |
| 47 |
readonly meta: M; |
| 48 |
/** The number of messages seen before the timeout */ |
| 49 |
readonly seen: number; |
| 50 |
/** The last message seen */ |
| 51 |
readonly lastValue: T | null; |
| 52 |
} |
| 53 |
|
| 54 |
/** |
| 55 |
* An error emitted when a timeout occurs. |
| 56 |
*/ |
| 57 |
export interface TimeoutError<T = unknown, M = unknown> extends Error { |
| 58 |
/** |
| 59 |
* The information provided to the error by the timeout |
| 60 |
* operation that created the error. Will be `null` if |
| 61 |
* used directly in non-RxJS code with an empty constructor. |
| 62 |
* (Note that using this constructor directly is not recommended, |
| 63 |
* you should create your own errors) |
| 64 |
*/ |
| 65 |
info: TimeoutInfo<T, M> | null; |
| 66 |
} |
| 67 |
|
| 68 |
export interface TimeoutErrorCtor { |
| 69 |
/** |
| 70 |
* @deprecated Internal implementation detail. Do not construct error instances. |
| 71 |
* Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269 |
| 72 |
*/ |
| 73 |
new <T = unknown, M = unknown>(info?: TimeoutInfo<T, M>): TimeoutError<T, M>; |
| 74 |
} |
| 75 |
|
| 76 |
/** |
| 77 |
* An error thrown by the {@link timeout} operator. |
| 78 |
* |
| 79 |
* Provided so users can use as a type and do quality comparisons. |
| 80 |
* We recommend you do not subclass this or create instances of this class directly. |
| 81 |
* If you have need of a error representing a timeout, you should |
| 82 |
* create your own error class and use that. |
| 83 |
* |
| 84 |
* @see {@link timeout} |
| 85 |
*/ |
| 86 |
export const TimeoutError: TimeoutErrorCtor = createErrorClass( |
| 87 |
(_super) => |
| 88 |
function TimeoutErrorImpl(this: any, info: TimeoutInfo<any> | null = null) { |
| 89 |
_super(this); |
| 90 |
this.message = 'Timeout has occurred'; |
| 91 |
this.name = 'TimeoutError'; |
| 92 |
this.info = info; |
| 93 |
} |
| 94 |
); |
| 95 |
|
| 96 |
/** |
| 97 |
* If `with` is provided, this will return an observable that will switch to a different observable if the source |
| 98 |
* does not push values within the specified time parameters. |
| 99 |
* |
| 100 |
* <span class="informal">The most flexible option for creating a timeout behavior.</span> |
| 101 |
* |
| 102 |
* The first thing to know about the configuration is if you do not provide a `with` property to the configuration, |
| 103 |
* when timeout conditions are met, this operator will emit a {@link TimeoutError}. Otherwise, it will use the factory |
| 104 |
* function provided by `with`, and switch your subscription to the result of that. Timeout conditions are provided by |
| 105 |
* the settings in `first` and `each`. |
| 106 |
* |
| 107 |
* The `first` property can be either a `Date` for a specific time, a `number` for a time period relative to the |
| 108 |
* point of subscription, or it can be skipped. This property is to check timeout conditions for the arrival of |
| 109 |
* the first value from the source _only_. The timings of all subsequent values from the source will be checked |
| 110 |
* against the time period provided by `each`, if it was provided. |
| 111 |
* |
| 112 |
* The `each` property can be either a `number` or skipped. If a value for `each` is provided, it represents the amount of |
| 113 |
* time the resulting observable will wait between the arrival of values from the source before timing out. Note that if |
| 114 |
* `first` is _not_ provided, the value from `each` will be used to check timeout conditions for the arrival of the first |
| 115 |
* value and all subsequent values. If `first` _is_ provided, `each` will only be use to check all values after the first. |
| 116 |
* |
| 117 |
* ## Examples |
| 118 |
* |
| 119 |
* Emit a custom error if there is too much time between values |
| 120 |
* |
| 121 |
* ```ts |
| 122 |
* import { interval, timeout, throwError } from 'rxjs'; |
| 123 |
* |
| 124 |
* class CustomTimeoutError extends Error { |
| 125 |
* constructor() { |
| 126 |
* super('It was too slow'); |
| 127 |
* this.name = 'CustomTimeoutError'; |
| 128 |
* } |
| 129 |
* } |
| 130 |
* |
| 131 |
* const slow$ = interval(900); |
| 132 |
* |
| 133 |
* slow$.pipe( |
| 134 |
* timeout({ |
| 135 |
* each: 1000, |
| 136 |
* with: () => throwError(() => new CustomTimeoutError()) |
| 137 |
* }) |
| 138 |
* ) |
| 139 |
* .subscribe({ |
| 140 |
* error: console.error |
| 141 |
* }); |
| 142 |
* ``` |
| 143 |
* |
| 144 |
* Switch to a faster observable if your source is slow. |
| 145 |
* |
| 146 |
* ```ts |
| 147 |
* import { interval, timeout } from 'rxjs'; |
| 148 |
* |
| 149 |
* const slow$ = interval(900); |
| 150 |
* const fast$ = interval(500); |
| 151 |
* |
| 152 |
* slow$.pipe( |
| 153 |
* timeout({ |
| 154 |
* each: 1000, |
| 155 |
* with: () => fast$, |
| 156 |
* }) |
| 157 |
* ) |
| 158 |
* .subscribe(console.log); |
| 159 |
* ``` |
| 160 |
* @param config The configuration for the timeout. |
| 161 |
*/ |
| 162 |
export function timeout<T, O extends ObservableInput<unknown>, M = unknown>( |
| 163 |
config: TimeoutConfig<T, O, M> & { with: (info: TimeoutInfo<T, M>) => O } |
| 164 |
): OperatorFunction<T, T | ObservedValueOf<O>>; |
| 165 |
|
| 166 |
/** |
| 167 |
* Returns an observable that will error or switch to a different observable if the source does not push values |
| 168 |
* within the specified time parameters. |
| 169 |
* |
| 170 |
* <span class="informal">The most flexible option for creating a timeout behavior.</span> |
| 171 |
* |
| 172 |
* The first thing to know about the configuration is if you do not provide a `with` property to the configuration, |
| 173 |
* when timeout conditions are met, this operator will emit a {@link TimeoutError}. Otherwise, it will use the factory |
| 174 |
* function provided by `with`, and switch your subscription to the result of that. Timeout conditions are provided by |
| 175 |
* the settings in `first` and `each`. |
| 176 |
* |
| 177 |
* The `first` property can be either a `Date` for a specific time, a `number` for a time period relative to the |
| 178 |
* point of subscription, or it can be skipped. This property is to check timeout conditions for the arrival of |
| 179 |
* the first value from the source _only_. The timings of all subsequent values from the source will be checked |
| 180 |
* against the time period provided by `each`, if it was provided. |
| 181 |
* |
| 182 |
* The `each` property can be either a `number` or skipped. If a value for `each` is provided, it represents the amount of |
| 183 |
* time the resulting observable will wait between the arrival of values from the source before timing out. Note that if |
| 184 |
* `first` is _not_ provided, the value from `each` will be used to check timeout conditions for the arrival of the first |
| 185 |
* value and all subsequent values. If `first` _is_ provided, `each` will only be use to check all values after the first. |
| 186 |
* |
| 187 |
* ### Handling TimeoutErrors |
| 188 |
* |
| 189 |
* If no `with` property was provided, subscriptions to the resulting observable may emit an error of {@link TimeoutError}. |
| 190 |
* The timeout error provides useful information you can examine when you're handling the error. The most common way to handle |
| 191 |
* the error would be with {@link catchError}, although you could use {@link tap} or just the error handler in your `subscribe` call |
| 192 |
* directly, if your error handling is only a side effect (such as notifying the user, or logging). |
| 193 |
* |
| 194 |
* In this case, you would check the error for `instanceof TimeoutError` to validate that the error was indeed from `timeout`, and |
| 195 |
* not from some other source. If it's not from `timeout`, you should probably rethrow it if you're in a `catchError`. |
| 196 |
* |
| 197 |
* ## Examples |
| 198 |
* |
| 199 |
* Emit a {@link TimeoutError} if the first value, and _only_ the first value, does not arrive within 5 seconds |
| 200 |
* |
| 201 |
* ```ts |
| 202 |
* import { interval, timeout } from 'rxjs'; |
| 203 |
* |
| 204 |
* // A random interval that lasts between 0 and 10 seconds per tick |
| 205 |
* const source$ = interval(Math.round(Math.random() * 10_000)); |
| 206 |
* |
| 207 |
* source$.pipe( |
| 208 |
* timeout({ first: 5_000 }) |
| 209 |
* ) |
| 210 |
* .subscribe({ |
| 211 |
* next: console.log, |
| 212 |
* error: console.error |
| 213 |
* }); |
| 214 |
* ``` |
| 215 |
* |
| 216 |
* Emit a {@link TimeoutError} if the source waits longer than 5 seconds between any two values or the first value |
| 217 |
* and subscription. |
| 218 |
* |
| 219 |
* ```ts |
| 220 |
* import { timer, timeout, expand } from 'rxjs'; |
| 221 |
* |
| 222 |
* const getRandomTime = () => Math.round(Math.random() * 10_000); |
| 223 |
* |
| 224 |
* // An observable that waits a random amount of time between each delivered value |
| 225 |
* const source$ = timer(getRandomTime()) |
| 226 |
* .pipe(expand(() => timer(getRandomTime()))); |
| 227 |
* |
| 228 |
* source$ |
| 229 |
* .pipe(timeout({ each: 5_000 })) |
| 230 |
* .subscribe({ |
| 231 |
* next: console.log, |
| 232 |
* error: console.error |
| 233 |
* }); |
| 234 |
* ``` |
| 235 |
* |
| 236 |
* Emit a {@link TimeoutError} if the source does not emit before 7 seconds, _or_ if the source waits longer than |
| 237 |
* 5 seconds between any two values after the first. |
| 238 |
* |
| 239 |
* ```ts |
| 240 |
* import { timer, timeout, expand } from 'rxjs'; |
| 241 |
* |
| 242 |
* const getRandomTime = () => Math.round(Math.random() * 10_000); |
| 243 |
* |
| 244 |
* // An observable that waits a random amount of time between each delivered value |
| 245 |
* const source$ = timer(getRandomTime()) |
| 246 |
* .pipe(expand(() => timer(getRandomTime()))); |
| 247 |
* |
| 248 |
* source$ |
| 249 |
* .pipe(timeout({ first: 7_000, each: 5_000 })) |
| 250 |
* .subscribe({ |
| 251 |
* next: console.log, |
| 252 |
* error: console.error |
| 253 |
* }); |
| 254 |
* ``` |
| 255 |
*/ |
| 256 |
export function timeout<T, M = unknown>(config: Omit<TimeoutConfig<T, any, M>, 'with'>): OperatorFunction<T, T>; |
| 257 |
|
| 258 |
/** |
| 259 |
* Returns an observable that will error if the source does not push its first value before the specified time passed as a `Date`. |
| 260 |
* This is functionally the same as `timeout({ first: someDate })`. |
| 261 |
* |
| 262 |
* <span class="informal">Errors if the first value doesn't show up before the given date and time</span> |
| 263 |
* |
| 264 |
*  |
| 265 |
* |
| 266 |
* @param first The date to at which the resulting observable will timeout if the source observable |
| 267 |
* does not emit at least one value. |
| 268 |
* @param scheduler The scheduler to use. Defaults to {@link asyncScheduler}. |
| 269 |
*/ |
| 270 |
export function timeout<T>(first: Date, scheduler?: SchedulerLike): MonoTypeOperatorFunction<T>; |
| 271 |
|
| 272 |
/** |
| 273 |
* Returns an observable that will error if the source does not push a value within the specified time in milliseconds. |
| 274 |
* This is functionally the same as `timeout({ each: milliseconds })`. |
| 275 |
* |
| 276 |
* <span class="informal">Errors if it waits too long between any value</span> |
| 277 |
* |
| 278 |
*  |
| 279 |
* |
| 280 |
* @param each The time allowed between each pushed value from the source before the resulting observable |
| 281 |
* will timeout. |
| 282 |
* @param scheduler The scheduler to use. Defaults to {@link asyncScheduler}. |
| 283 |
*/ |
| 284 |
export function timeout<T>(each: number, scheduler?: SchedulerLike): MonoTypeOperatorFunction<T>; |
| 285 |
|
| 286 |
/** |
| 287 |
* |
| 288 |
* Errors if Observable does not emit a value in given time span. |
| 289 |
* |
| 290 |
* <span class="informal">Timeouts on Observable that doesn't emit values fast enough.</span> |
| 291 |
* |
| 292 |
*  |
| 293 |
* |
| 294 |
* @see {@link timeoutWith} |
| 295 |
* |
| 296 |
* @return A function that returns an Observable that mirrors behaviour of the |
| 297 |
* source Observable, unless timeout happens when it throws an error. |
| 298 |
*/ |
| 299 |
export function timeout<T, O extends ObservableInput<any>, M>( |
| 300 |
config: number | Date | TimeoutConfig<T, O, M>, |
| 301 |
schedulerArg?: SchedulerLike |
| 302 |
): OperatorFunction<T, T | ObservedValueOf<O>> { |
| 303 |
// Intentionally terse code. |
| 304 |
// If the first argument is a valid `Date`, then we use it as the `first` config. |
| 305 |
// Otherwise, if the first argument is a `number`, then we use it as the `each` config. |
| 306 |
// Otherwise, it can be assumed the first argument is the configuration object itself, and |
| 307 |
// we destructure that into what we're going to use, setting important defaults as we do. |
| 308 |
// NOTE: The default for `scheduler` will be the `scheduler` argument if it exists, or |
| 309 |
// it will default to the `asyncScheduler`. |
| 310 |
const { |
| 311 |
first, |
| 312 |
each, |
| 313 |
with: _with = timeoutErrorFactory, |
| 314 |
scheduler = schedulerArg ?? asyncScheduler, |
| 315 |
meta = null!, |
| 316 |
} = (isValidDate(config) ? { first: config } : typeof config === 'number' ? { each: config } : config) as TimeoutConfig<T, O, M>; |
| 317 |
|
| 318 |
if (first == null && each == null) { |
| 319 |
// Ensure timeout was provided at runtime. |
| 320 |
throw new TypeError('No timeout provided.'); |
| 321 |
} |
| 322 |
|
| 323 |
return operate((source, subscriber) => { |
| 324 |
// This subscription encapsulates our subscription to the |
| 325 |
// source for this operator. We're capturing it separately, |
| 326 |
// because if there is a `with` observable to fail over to, |
| 327 |
// we want to unsubscribe from our original subscription, and |
| 328 |
// hand of the subscription to that one. |
| 329 |
let originalSourceSubscription: Subscription; |
| 330 |
// The subscription for our timeout timer. This changes |
| 331 |
// every time we get a new value. |
| 332 |
let timerSubscription: Subscription; |
| 333 |
// A bit of state we pass to our with and error factories to |
| 334 |
// tell what the last value we saw was. |
| 335 |
let lastValue: T | null = null; |
| 336 |
// A bit of state we pass to the with and error factories to |
| 337 |
// tell how many values we have seen so far. |
| 338 |
let seen = 0; |
| 339 |
const startTimer = (delay: number) => { |
| 340 |
timerSubscription = executeSchedule( |
| 341 |
subscriber, |
| 342 |
scheduler, |
| 343 |
() => { |
| 344 |
try { |
| 345 |
originalSourceSubscription.unsubscribe(); |
| 346 |
innerFrom( |
| 347 |
_with!({ |
| 348 |
meta, |
| 349 |
lastValue, |
| 350 |
seen, |
| 351 |
}) |
| 352 |
).subscribe(subscriber); |
| 353 |
} catch (err) { |
| 354 |
subscriber.error(err); |
| 355 |
} |
| 356 |
}, |
| 357 |
delay |
| 358 |
); |
| 359 |
}; |
| 360 |
|
| 361 |
originalSourceSubscription = source.subscribe( |
| 362 |
createOperatorSubscriber( |
| 363 |
subscriber, |
| 364 |
(value: T) => { |
| 365 |
// clear the timer so we can emit and start another one. |
| 366 |
timerSubscription?.unsubscribe(); |
| 367 |
seen++; |
| 368 |
// Emit |
| 369 |
subscriber.next((lastValue = value)); |
| 370 |
// null | undefined are both < 0. Thanks, JavaScript. |
| 371 |
each! > 0 && startTimer(each!); |
| 372 |
}, |
| 373 |
undefined, |
| 374 |
undefined, |
| 375 |
() => { |
| 376 |
if (!timerSubscription?.closed) { |
| 377 |
timerSubscription?.unsubscribe(); |
| 378 |
} |
| 379 |
// Be sure not to hold the last value in memory after unsubscription |
| 380 |
// it could be quite large. |
| 381 |
lastValue = null; |
| 382 |
} |
| 383 |
) |
| 384 |
); |
| 385 |
|
| 386 |
// Intentionally terse code. |
| 387 |
// If we've `seen` a value, that means the "first" clause was met already, if it existed. |
| 388 |
// it also means that a timer was already started for "each" (in the next handler above). |
| 389 |
// If `first` was provided, and it's a number, then use it. |
| 390 |
// If `first` was provided and it's not a number, it's a Date, and we get the difference between it and "now". |
| 391 |
// If `first` was not provided at all, then our first timer will be the value from `each`. |
| 392 |
!seen && startTimer(first != null ? (typeof first === 'number' ? first : +first - scheduler!.now()) : each!); |
| 393 |
}); |
| 394 |
} |
| 395 |
|
| 396 |
/** |
| 397 |
* The default function to use to emit an error when timeout occurs and a `with` function |
| 398 |
* is not specified. |
| 399 |
* @param info The information about the timeout to pass along to the error |
| 400 |
*/ |
| 401 |
function timeoutErrorFactory(info: TimeoutInfo<any>): Observable<never> { |
| 402 |
throw new TimeoutError(info); |
| 403 |
} |