diff --git a/.prettierrc.json b/.prettierrc.json index 5d6fdea4b44..e2ac81214b6 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -2,10 +2,11 @@ "trailingComma": "es5", "singleQuote": true, "printWidth": 140, + "arrowParens": "avoid", "overrides": [{ "files": ["spec/**/*.ts", "spec-dtslint/**/*.ts"], "options": { "requirePragma": true } }] -} \ No newline at end of file +} diff --git a/README.md b/README.md index 24de33ab0b9..f15e29c1ae3 100644 --- a/README.md +++ b/README.md @@ -36,15 +36,29 @@ By contributing or commenting on issues in this repository, whether you've read ### ES6 via npm -```sh +```shell npm install rxjs ``` -It's recommended to pull in the Observable creation methods you need directly from `'rxjs'` as shown below with `range`. And you can pull in any operator you need from one spot, under `'rxjs/operators'`. +It's recommended to pull in the Observable creation methods you need directly from `'rxjs'` as shown below with `range`. +If you're using RxJS version 7.2 or above, you can pull in any operator you need from the same spot, `'rxjs'`. ```ts -import { range } from "rxjs"; -import { map, filter } from "rxjs/operators"; +import { range, filter, map } from 'rxjs'; + +range(1, 200) + .pipe( + filter(x => x % 2 === 1), + map(x => x + x) + ) + .subscribe(x => console.log(x)); +``` + +If you're using RxJS version below 7.2, you can pull in any operator you need from one spot, under `'rxjs/operators'`. + +```ts +import { range } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; range(1, 200) .pipe( @@ -64,7 +78,7 @@ The global namespace for rxjs is `rxjs`: ```js const { range } = rxjs; -const { map, filter } = rxjs.operators; +const { filter, map } = rxjs.operators; range(1, 200) .pipe( diff --git a/docs_app/tools/transforms/angular.io-package/processors/cleanGeneratedFiles.js b/docs_app/tools/transforms/angular.io-package/processors/cleanGeneratedFiles.js index 8ff08548ebe..b2ad51807c5 100644 --- a/docs_app/tools/transforms/angular.io-package/processors/cleanGeneratedFiles.js +++ b/docs_app/tools/transforms/angular.io-package/processors/cleanGeneratedFiles.js @@ -3,8 +3,8 @@ module.exports = function cleanGeneratedFiles() { return { $runAfter: ['writing-files'], $runBefore: ['writeFilesProcessor'], - $process: function() { - rimraf.sync('src/generated/{*.json}'); - } + $process: function () { + rimraf.sync('src/generated/{docs,*.json}'); + }, }; }; diff --git a/src/internal/Observable.ts b/src/internal/Observable.ts index aca3a3add86..0f00105cdcf 100644 --- a/src/internal/Observable.ts +++ b/src/internal/Observable.ts @@ -124,8 +124,10 @@ export class Observable implements Subscribable { * by default emits all its values synchronously. Always check documentation for how given Observable * will behave when subscribed and if its default behavior can be modified with a `scheduler`. * - * ## Example - * ### Subscribe with an Observer + * ## Examples + * + * Subscribe with an {@link guide/observer Observer} + * * ```ts * import { of } from 'rxjs'; * @@ -148,13 +150,14 @@ export class Observable implements Subscribable { * .subscribe(sumObserver); * * // Logs: - * // "Adding: 1" - * // "Adding: 2" - * // "Adding: 3" - * // "Sum equals: 6" + * // 'Adding: 1' + * // 'Adding: 2' + * // 'Adding: 3' + * // 'Sum equals: 6' * ``` * - * ### Subscribe with functions + * Subscribe with functions ({@link deprecations/subscribe-arguments deprecated}) + * * ```ts * import { of } from 'rxjs' * @@ -170,13 +173,14 @@ export class Observable implements Subscribable { * ); * * // Logs: - * // "Adding: 1" - * // "Adding: 2" - * // "Adding: 3" - * // "Sum equals: 6" + * // 'Adding: 1' + * // 'Adding: 2' + * // 'Adding: 3' + * // 'Sum equals: 6' * ``` * - * ### Cancel a subscription + * Cancel a subscription + * * ```ts * import { interval } from 'rxjs'; * @@ -198,14 +202,14 @@ export class Observable implements Subscribable { * // Logs: * // 0 after 1s * // 1 after 2s - * // "unsubscribed!" after 2.5s + * // 'unsubscribed!' after 2.5s * ``` * * @param {Observer|Function} observerOrNext (optional) Either an observer with methods to be called, - * or the first of three possible handlers, which is the handler for each value emitted from the subscribed - * Observable. + * or the first of three possible handlers, which is the handler for each value emitted from the subscribed + * Observable. * @param {Function} error (optional) A handler for a terminal event resulting from an error. If no error handler is provided, - * the error will be thrown asynchronously as unhandled. + * the error will be thrown asynchronously as unhandled. * @param {Function} complete (optional) A handler for a terminal event resulting from successful completion. * @return {Subscription} a subscription reference to the registered handlers * @method subscribe @@ -260,36 +264,36 @@ export class Observable implements Subscribable { * this situation, look into adding something like {@link timeout}, {@link take}, * {@link takeWhile}, or {@link takeUntil} amongst others. * - * ### Example: + * ## Example * * ```ts - * import { interval } from 'rxjs'; - * import { take } from 'rxjs/operators'; + * import { interval, take } from 'rxjs'; * * const source$ = interval(1000).pipe(take(4)); * * async function getTotal() { - * let total = 0; + * let total = 0; * - * await source$.forEach(value => { - * total += value; - * console.log('observable -> ', value); - * }); + * await source$.forEach(value => { + * total += value; + * console.log('observable -> ' + value); + * }); * - * return total; + * return total; * } * * getTotal().then( - * total => console.log('Total:', total) - * ) + * total => console.log('Total: ' + total) + * ); * * // Expected: - * // "observable -> 0" - * // "observable -> 1" - * // "observable -> 2" - * // "observable -> 3" - * // "Total: 6" + * // 'observable -> 0' + * // 'observable -> 1' + * // 'observable -> 2' + * // 'observable -> 3' + * // 'Total: 6' * ``` + * * @param next a handler for each value emitted by the observable * @return a promise that either resolves on observable completion or * rejects with the handled error @@ -317,7 +321,7 @@ export class Observable implements Subscribable { // accessing subscription below in the closure due to Temporal Dead Zone. let subscription: Subscription; subscription = this.subscribe( - (value) => { + value => { try { next(value); } catch (err) { @@ -421,10 +425,10 @@ export class Observable implements Subscribable { * @return {Observable} the Observable result of all of the operators having * been called in the order they were passed in. * - * ### Example + * ## Example + * * ```ts - * import { interval } from 'rxjs'; - * import { map, filter, scan } from 'rxjs/operators'; + * import { interval, filter, map, scan } from 'rxjs'; * * interval(1000) * .pipe( @@ -432,7 +436,7 @@ export class Observable implements Subscribable { * map(x => x + x), * scan((acc, x) => acc + x) * ) - * .subscribe(x => console.log(x)) + * .subscribe(x => console.log(x)); * ``` */ pipe(...operations: OperatorFunction[]): Observable { diff --git a/src/internal/ajax/ajax.ts b/src/internal/ajax/ajax.ts index e54e2cbd4c7..f6700cb7151 100644 --- a/src/internal/ajax/ajax.ts +++ b/src/internal/ajax/ajax.ts @@ -12,16 +12,16 @@ export interface AjaxCreationMethod { * * This is the most configurable option, and the basis for all other AJAX calls in the library. * - * ### Example + * ## Example + * * ```ts * import { ajax } from 'rxjs/ajax'; - * import { map, catchError } from 'rxjs/operators'; - * import { of } from 'rxjs'; + * import { map, catchError, of } from 'rxjs'; * * const obs$ = ajax({ - * method: 'GET', - * url: `https://api.github.com/users?per_page=5`, - * responseType: 'json', + * method: 'GET', + * url: 'https://api.github.com/users?per_page=5', + * responseType: 'json', * }).pipe( * map(userResponse => console.log('users: ', userResponse)), * catchError(error => { @@ -38,13 +38,13 @@ export interface AjaxCreationMethod { * [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) in * global scope. Defaults to a `responseType` of `"json"`. * - * ### Example + * ## Example + * * ```ts * import { ajax } from 'rxjs/ajax'; - * import { map, catchError } from 'rxjs/operators'; - * import { of } from 'rxjs'; + * import { map, catchError, of } from 'rxjs'; * - * const obs$ = ajax(`https://api.github.com/users?per_page=5`).pipe( + * const obs$ = ajax('https://api.github.com/users?per_page=5').pipe( * map(userResponse => console.log('users: ', userResponse)), * catchError(error => { * console.log('error: ', error); @@ -173,29 +173,35 @@ function ajaxGetJSON(url: string, headers?: Record): Observab * It creates an observable for an Ajax request with either a request object with * url, headers, etc or a string for a URL. * + * ## Examples + * + * Using `ajax()` to fetch the response object that is being returned from API * - * ## Using ajax() to fetch the response object that is being returned from API. * ```ts * import { ajax } from 'rxjs/ajax'; - * import { map, catchError } from 'rxjs/operators'; - * import { of } from 'rxjs'; + * import { map, catchError, of } from 'rxjs'; * - * const obs$ = ajax(`https://api.github.com/users?per_page=5`).pipe( + * const obs$ = ajax('https://api.github.com/users?per_page=5').pipe( * map(userResponse => console.log('users: ', userResponse)), * catchError(error => { * console.log('error: ', error); * return of(error); * }) * ); + * + * obs$.subscribe({ + * next: value => console.log(value), + * error: err => console.log(err), + * }); * ``` * - * ## Using ajax.getJSON() to fetch data from API. + * Using `ajax.getJSON()` to fetch data from API + * * ```ts * import { ajax } from 'rxjs/ajax'; - * import { map, catchError } from 'rxjs/operators'; - * import { of } from 'rxjs'; + * import { map, catchError, of } from 'rxjs'; * - * const obs$ = ajax.getJSON(`https://api.github.com/users?per_page=5`).pipe( + * const obs$ = ajax.getJSON('https://api.github.com/users?per_page=5').pipe( * map(userResponse => console.log('users: ', userResponse)), * catchError(error => { * console.log('error: ', error); @@ -203,13 +209,17 @@ function ajaxGetJSON(url: string, headers?: Record): Observab * }) * ); * + * obs$.subscribe({ + * next: value => console.log(value), + * error: err => console.log(err), + * }); * ``` * - * ## Using ajax() with object as argument and method POST with a two seconds delay. + * Using `ajax()` with object as argument and method POST with a two seconds delay + * * ```ts * import { ajax } from 'rxjs/ajax'; - * import { map, catchError } from 'rxjs/operators'; - * import { of } from 'rxjs'; + * import { map, catchError, of } from 'rxjs'; * * const users = ajax({ * url: 'https://httpbin.org/delay/2', @@ -229,15 +239,19 @@ function ajaxGetJSON(url: string, headers?: Record): Observab * }) * ); * + * users.subscribe({ + * next: value => console.log(value), + * error: err => console.log(err), + * }); * ``` * - * ## Using ajax() to fetch. An error object that is being returned from the request. + * Using ajax() to fetch. An error object that is being returned from the request + * * ```ts * import { ajax } from 'rxjs/ajax'; - * import { map, catchError } from 'rxjs/operators'; - * import { of } from 'rxjs'; + * import { map, catchError, of } from 'rxjs'; * - * const obs$ = ajax(`https://api.github.com/404`).pipe( + * const obs$ = ajax('https://api.github.com/404').pipe( * map(userResponse => console.log('users: ', userResponse)), * catchError(error => { * console.log('error: ', error); @@ -245,6 +259,10 @@ function ajaxGetJSON(url: string, headers?: Record): Observab * }) * ); * + * obs$.subscribe({ + * next: value => console.log(value), + * error: err => console.log(err), + * }); * ``` */ export const ajax: AjaxCreationMethod = (() => { @@ -275,7 +293,7 @@ const PROGRESS = 'progress'; const LOAD = 'load'; export function fromAjax(config: AjaxConfig): Observable> { - return new Observable((destination) => { + return new Observable(destination => { // Here we're pulling off each of the configuration arguments // that we don't want to add to the request information we're // passing around. @@ -433,15 +451,15 @@ export function fromAjax(config: AjaxConfig): Observable> { }; if (includeUploadProgress) { - [LOADSTART, PROGRESS, LOAD].forEach((type) => addProgressEvent(xhr.upload, type, UPLOAD)); + [LOADSTART, PROGRESS, LOAD].forEach(type => addProgressEvent(xhr.upload, type, UPLOAD)); } if (progressSubscriber) { - [LOADSTART, PROGRESS].forEach((type) => xhr.upload.addEventListener(type, (e: any) => progressSubscriber?.next?.(e))); + [LOADSTART, PROGRESS].forEach(type => xhr.upload.addEventListener(type, (e: any) => progressSubscriber?.next?.(e))); } if (includeDownloadProgress) { - [LOADSTART, PROGRESS].forEach((type) => addProgressEvent(xhr, type, DOWNLOAD)); + [LOADSTART, PROGRESS].forEach(type => addProgressEvent(xhr, type, DOWNLOAD)); } const emitError = (status?: number) => { @@ -449,12 +467,12 @@ export function fromAjax(config: AjaxConfig): Observable> { destination.error(new AjaxError(msg, xhr, _request)); }; - xhr.addEventListener('error', (e) => { + xhr.addEventListener('error', e => { progressSubscriber?.error?.(e); emitError(); }); - xhr.addEventListener(LOAD, (event) => { + xhr.addEventListener(LOAD, event => { const { status } = xhr; // 4xx and 5xx should error (https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) if (status < 400) { diff --git a/src/internal/firstValueFrom.ts b/src/internal/firstValueFrom.ts index de6e237c63b..02768aecaa3 100644 --- a/src/internal/firstValueFrom.ts +++ b/src/internal/firstValueFrom.ts @@ -28,10 +28,10 @@ export function firstValueFrom(source: Observable): Promise; * something like {@link timeout}, {@link take}, {@link takeWhile}, or {@link takeUntil} * amongst others. * - * ### Example + * ## Example * * Wait for the first value from a stream and emit it from a promise in - * an async function. + * an async function * * ```ts * import { interval, firstValueFrom } from 'rxjs'; @@ -39,13 +39,13 @@ export function firstValueFrom(source: Observable): Promise; * async function execute() { * const source$ = interval(2000); * const firstNumber = await firstValueFrom(source$); - * console.log(`The first number is ${firstNumber}`); + * console.log(`The first number is ${ firstNumber }`); * } * * execute(); * * // Expected output: - * // "The first number is 0" + * // 'The first number is 0' * ``` * * @see {@link lastValueFrom} @@ -57,7 +57,7 @@ export function firstValueFrom(source: Observable, config?: FirstValueF const hasConfig = typeof config === 'object'; return new Promise((resolve, reject) => { const subscriber = new SafeSubscriber({ - next: (value) => { + next: value => { resolve(value); subscriber.unsubscribe(); }, diff --git a/src/internal/lastValueFrom.ts b/src/internal/lastValueFrom.ts index b70000f47e5..199c745c7cf 100644 --- a/src/internal/lastValueFrom.ts +++ b/src/internal/lastValueFrom.ts @@ -26,25 +26,24 @@ export function lastValueFrom(source: Observable): Promise; * this situation, look into adding something like {@link timeout}, {@link take}, * {@link takeWhile}, or {@link takeUntil} amongst others. * - * ### Example + * ## Example * * Wait for the last value from a stream and emit it from a promise in - * an async function. + * an async function * * ```ts - * import { interval, lastValueFrom } from 'rxjs'; - * import { take } from 'rxjs/operators'; + * import { interval, take, lastValueFrom } from 'rxjs'; * * async function execute() { * const source$ = interval(2000).pipe(take(10)); * const finalNumber = await lastValueFrom(source$); - * console.log(`The final number is ${finalNumber}`); + * console.log(`The final number is ${ finalNumber }`); * } * * execute(); * * // Expected output: - * // "The final number is 9" + * // 'The final number is 9' * ``` * * @see {@link firstValueFrom} @@ -58,7 +57,7 @@ export function lastValueFrom(source: Observable, config?: LastValueFro let _hasValue = false; let _value: T; source.subscribe({ - next: (value) => { + next: value => { _value = value; _hasValue = true; }, diff --git a/src/internal/observable/combineLatest.ts b/src/internal/observable/combineLatest.ts index b207405fe9e..400a6f6c984 100644 --- a/src/internal/observable/combineLatest.ts +++ b/src/internal/observable/combineLatest.ts @@ -110,7 +110,9 @@ export function combineLatest>>( * will error immediately as well, and all other Observables will be unsubscribed. * * ## Examples - * ### Combine two timer Observables + * + * Combine two timer Observables + * * ```ts * import { combineLatest, timer } from 'rxjs'; * @@ -124,10 +126,11 @@ export function combineLatest>>( * // [1, 1] after 1.5s * // [2, 1] after 2s * ``` - * ### Combine a dictionary of Observables + * + * Combine a dictionary of Observables + * * ```ts - * import { combineLatest, of } from 'rxjs'; - * import { delay, startWith } from 'rxjs/operators'; + * import { of, delay, startWith, combineLatest } from 'rxjs'; * * const observables = { * a: of(1).pipe(delay(1000), startWith(0)), @@ -137,20 +140,21 @@ export function combineLatest>>( * const combined = combineLatest(observables); * combined.subscribe(value => console.log(value)); * // Logs - * // {a: 0, b: 0, c: 0} immediately - * // {a: 1, b: 0, c: 0} after 1s - * // {a: 1, b: 5, c: 0} after 5s - * // {a: 1, b: 5, c: 10} after 10s + * // { a: 0, b: 0, c: 0 } immediately + * // { a: 1, b: 0, c: 0 } after 1s + * // { a: 1, b: 5, c: 0 } after 5s + * // { a: 1, b: 5, c: 10 } after 10s * ``` - * ### Combine an array of Observables + * + * Combine an array of Observables + * * ```ts - * import { combineLatest, of } from 'rxjs'; - * import { delay, startWith } from 'rxjs/operators'; + * import { of, delay, startWith, combineLatest } from 'rxjs'; * * const observables = [1, 5, 10].map( * n => of(n).pipe( - * delay(n * 1000), // emit 0 and then emit n after n seconds - * startWith(0), + * delay(n * 1000), // emit 0 and then emit n after n seconds + * startWith(0) * ) * ); * const combined = combineLatest(observables); @@ -162,11 +166,10 @@ export function combineLatest>>( * // [1, 5, 10] after 10s * ``` * + * Use map operator to dynamically calculate the Body-Mass Index * - * ### Use map operator to dynamically calculate the Body-Mass Index * ```ts - * import { combineLatest, of } from 'rxjs'; - * import { map } from 'rxjs/operators'; + * import { of, combineLatest, map } from 'rxjs'; * * const weight = of(70, 72, 76, 79, 75); * const height = of(1.76, 1.77, 1.78); @@ -214,7 +217,7 @@ export function combineLatest, R>(...args: any[]) scheduler, keys ? // A handler for scrubbing the array of args into a dictionary. - (values) => createObject(keys, values) + values => createObject(keys, values) : // A passthrough to just return the array identity ) @@ -255,7 +258,7 @@ export function combineLatestInit( source.subscribe( new OperatorSubscriber( subscriber, - (value) => { + value => { // When we get a value, record it in our set of values. values[i] = value; if (!hasFirstValue) { diff --git a/src/internal/observable/concat.ts b/src/internal/observable/concat.ts index 230c1a7bb9c..75f9722f02d 100644 --- a/src/internal/observable/concat.ts +++ b/src/internal/observable/concat.ts @@ -47,10 +47,11 @@ export function concat( * you can always use {@link repeat}. * * ## Examples - * ### Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10 + * + * Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10 + * * ```ts - * import { concat, interval, range } from 'rxjs'; - * import { take } from 'rxjs/operators'; + * import { interval, take, range, concat } from 'rxjs'; * * const timer = interval(1000).pipe(take(4)); * const sequence = range(1, 10); @@ -61,10 +62,10 @@ export function concat( * // 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10 * ``` * - * ### Concatenate 3 Observables + * Concatenate 3 Observables + * * ```ts - * import { concat, interval } from 'rxjs'; - * import { take } from 'rxjs/operators'; + * import { interval, take, concat } from 'rxjs'; * * const timer1 = interval(1000).pipe(take(10)); * const timer2 = interval(2000).pipe(take(6)); @@ -80,26 +81,25 @@ export function concat( * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9 * ``` * - * ### Concatenate the same Observable to repeat it + * Concatenate the same Observable to repeat it + * * ```ts - * import { concat, interval } from 'rxjs'; - * import { take } from 'rxjs/operators'; + * import { interval, take, concat } from 'rxjs'; * * const timer = interval(1000).pipe(take(2)); * * concat(timer, timer) // concatenating the same Observable! - * .subscribe( - * value => console.log(value), - * err => {}, - * () => console.log('...and it is done!') - * ); + * .subscribe({ + * next: value => console.log(value), + * complete: () => console.log('...and it is done!') + * }); * * // Logs: * // 0 after 1s * // 1 after 2s * // 0 after 3s * // 1 after 4s - * // "...and it is done!" also after 4s + * // '...and it is done!' also after 4s * ``` * * @see {@link concatAll} @@ -108,11 +108,7 @@ export function concat( * @see {@link startWith} * @see {@link endWith} * - * @param input1 An input Observable to concatenate with others. - * @param input2 An input Observable to concatenate with others. - * More than one input Observables may be given as argument. - * @param scheduler An optional {@link SchedulerLike} to schedule each - * Observable subscription on. + * @param args Input Observables to concatenate. */ export function concat(...args: any[]): Observable { return concatAll()(from(args, popScheduler(args))); diff --git a/src/internal/observable/defer.ts b/src/internal/observable/defer.ts index 417f8677906..51246f38f27 100644 --- a/src/internal/observable/defer.ts +++ b/src/internal/observable/defer.ts @@ -21,11 +21,13 @@ import { innerFrom } from './innerFrom'; * function call is transferred to the Observer by calling `error`. * * ## Example - * ### Subscribe to either an Observable of clicks or an Observable of interval, at random + * + * Subscribe to either an Observable of clicks or an Observable of interval, at random + * * ```ts * import { defer, fromEvent, interval } from 'rxjs'; * - * const clicksOrInterval = defer(function () { + * const clicksOrInterval = defer(() => { * return Math.random() > 0.5 * ? fromEvent(document, 'click') * : interval(1000); @@ -49,7 +51,7 @@ import { innerFrom } from './innerFrom'; * an invocation of the given Observable factory function. */ export function defer>(observableFactory: () => R): Observable> { - return new Observable>((subscriber) => { + return new Observable>(subscriber => { innerFrom(observableFactory()).subscribe(subscriber); }); } diff --git a/src/internal/observable/dom/WebSocketSubject.ts b/src/internal/observable/dom/WebSocketSubject.ts index 05d9fc4aaeb..be180964b9e 100644 --- a/src/internal/observable/dom/WebSocketSubject.ts +++ b/src/internal/observable/dom/WebSocketSubject.ts @@ -17,88 +17,92 @@ import { Observer, NextObserver } from '../../types'; * use `openObserver`, when the connection is closed `closeObserver`, if we * are interested in listening for data coming from server: `deserializer`, * which allows us to customize the deserialization strategy of data before passing it - * to the socket client. By default `deserializer` is going to apply `JSON.parse` to each message coming + * to the socket client. By default, `deserializer` is going to apply `JSON.parse` to each message coming * from the Server. * - * ## Example + * ## Examples + * * **deserializer**, the default for this property is `JSON.parse` but since there are just two options * for incoming data, either be text or binarydata. We can apply a custom deserialization strategy * or just simply skip the default behaviour. + * * ```ts * import { webSocket } from 'rxjs/webSocket'; * * const wsSubject = webSocket({ - * url: 'ws://localhost:8081', - * //Apply any transformation of your choice. - * deserializer: ({data}) => data + * url: 'ws://localhost:8081', + * //Apply any transformation of your choice. + * deserializer: ({ data }) => data * }); * * wsSubject.subscribe(console.log); * - * // Let's suppose we have this on the Server: ws.send("This is a msg from the server") + * // Let's suppose we have this on the Server: ws.send('This is a msg from the server') * //output * // * // This is a msg from the server * ``` * - * **serializer** allows us to apply custom serialization strategy but for the outgoing messages + * **serializer** allows us to apply custom serialization strategy but for the outgoing messages. + * * ```ts * import { webSocket } from 'rxjs/webSocket'; * * const wsSubject = webSocket({ - * url: 'ws://localhost:8081', - * //Apply any transformation of your choice. - * serializer: msg => JSON.stringify({channel: "webDevelopment", msg: msg}) + * url: 'ws://localhost:8081', + * // Apply any transformation of your choice. + * serializer: msg => JSON.stringify({ channel: 'webDevelopment', msg: msg }) * }); * - * wsSubject.subscribe(() => subject.next("msg to the server")); + * wsSubject.subscribe(() => subject.next('msg to the server')); * * // Let's suppose we have this on the Server: - * // ws.on("message", msg => console.log); - * // ws.send("This is a msg from the server"); - * //output at server side: + * // ws.on('message', msg => console.log); + * // ws.send('This is a msg from the server'); + * // output at server side: * // * // {"channel":"webDevelopment","msg":"msg to the server"} * ``` * - * **closeObserver** allows us to set a custom error when an error raise up. + * **closeObserver** allows us to set a custom error when an error raises up. + * * ```ts * import { webSocket } from 'rxjs/webSocket'; * * const wsSubject = webSocket({ - * url: 'ws://localhost:8081', - * closeObserver: { - next(closeEvent) { - const customError = { code: 6666, reason: "Custom evil reason" } - console.log(`code: ${customError.code}, reason: ${customError.reason}`); - } - } + * url: 'ws://localhost:8081', + * closeObserver: { + * next() { + * const customError = { code: 6666, reason: 'Custom evil reason' } + * console.log(`code: ${ customError.code }, reason: ${ customError.reason }`); + * } + * } * }); * - * //output + * // output * // code: 6666, reason: Custom evil reason * ``` * * **openObserver**, Let's say we need to make some kind of init task before sending/receiving msgs to the * webSocket or sending notification that the connection was successful, this is when * openObserver is useful for. + * * ```ts * import { webSocket } from 'rxjs/webSocket'; * * const wsSubject = webSocket({ - * url: 'ws://localhost:8081', - * openObserver: { - * next: () => { - * console.log('connetion ok'); - * } - * }, + * url: 'ws://localhost:8081', + * openObserver: { + * next: () => { + * console.log('Connection ok'); + * } + * } * }); * - * //output - * // connetion ok` + * // output + * // Connection ok * ``` - * */ - + */ export interface WebSocketSubjectConfig { /** The url of the socket server to connect to */ url: string; @@ -121,7 +125,7 @@ export interface WebSocketSubjectConfig { */ openObserver?: NextObserver; /** - * An Observer then watches when close events occur on the underlying webSocket + * An Observer that watches when close events occur on the underlying web socket */ closeObserver?: NextObserver; /** @@ -231,7 +235,7 @@ export class WebSocketSubject extends AnonymousSubject { } const subscription = self.subscribe( - (x) => { + x => { try { if (messageFilter(x)) { observer.next(x); @@ -240,7 +244,7 @@ export class WebSocketSubject extends AnonymousSubject { observer.error(err); } }, - (err) => observer.error(err), + err => observer.error(err), () => observer.complete() ); @@ -293,7 +297,7 @@ export class WebSocketSubject extends AnonymousSubject { const queue = this.destination; this.destination = Subscriber.create( - (x) => { + x => { if (socket!.readyState === 1) { try { const { serializer } = this._config; @@ -303,7 +307,7 @@ export class WebSocketSubject extends AnonymousSubject { } } }, - (err) => { + err => { const { closingObserver } = this._config; if (closingObserver) { closingObserver.next(undefined); diff --git a/src/internal/observable/dom/animationFrames.ts b/src/internal/observable/dom/animationFrames.ts index 7ac4bfca827..6ebbdf0b751 100644 --- a/src/internal/observable/dom/animationFrames.ts +++ b/src/internal/observable/dom/animationFrames.ts @@ -1,13 +1,13 @@ import { Observable } from '../../Observable'; import { Subscription } from '../../Subscription'; -import { TimestampProvider } from "../../types"; +import { TimestampProvider } from '../../types'; import { performanceTimestampProvider } from '../../scheduler/performanceTimestampProvider'; import { animationFrameProvider } from '../../scheduler/animationFrameProvider'; /** * An observable of animation frames * - * Emits the the amount of time elapsed since subscription and the timestamp on each animation frame. + * Emits the amount of time elapsed since subscription and the timestamp on each animation frame. * Defaults to milliseconds provided to the requestAnimationFrame's callback. Does not end on its own. * * Every subscription will start a separate animation loop. Since animation frames are always scheduled @@ -19,19 +19,18 @@ import { animationFrameProvider } from '../../scheduler/animationFrameProvider'; * * This is useful for setting up animations with RxJS. * - * ### Example + * ## Examples * * Tweening a div to move it on the screen * * ```ts - * import { animationFrames } from 'rxjs'; - * import { map, takeWhile, endWith } from 'rxjs/operators'; + * import { animationFrames, map, takeWhile, endWith } from 'rxjs'; * * function tween(start: number, end: number, duration: number) { * const diff = end - start; * return animationFrames().pipe( * // Figure out what percentage of time has passed - * map(({elapsed}) => elapsed / duration), + * map(({ elapsed }) => elapsed / duration), * // Take the vector while less than 100% * takeWhile(v => v < 1), * // Finish with 100% @@ -51,12 +50,10 @@ import { animationFrameProvider } from '../../scheduler/animationFrameProvider'; * div.style.transform = 'translate3d(10px, 0, 0)'; * * tween(10, 200, 4000).subscribe(x => { - * div.style.transform = `translate3d(${x}px, 0, 0)`; + * div.style.transform = `translate3d(${ x }px, 0, 0)`; * }); * ``` * - * ### Example - * * Providing a custom timestamp provider * * ```ts @@ -86,7 +83,7 @@ export function animationFrames(timestampProvider?: TimestampProvider) { */ function animationFramesFactory(timestampProvider?: TimestampProvider) { const { schedule } = animationFrameProvider; - return new Observable<{ timestamp: number, elapsed: number }>(subscriber => { + return new Observable<{ timestamp: number; elapsed: number }>(subscriber => { const subscription = new Subscription(); // If no timestamp provider is specified, use performance.now() - as it // will return timestamps 'compatible' with those passed to the run @@ -108,7 +105,7 @@ function animationFramesFactory(timestampProvider?: TimestampProvider) { const now = provider.now(); subscriber.next({ timestamp: timestampProvider ? now : timestamp, - elapsed: now - start + elapsed: now - start, }); if (!subscriber.closed) { subscription.add(schedule(run)); diff --git a/src/internal/observable/dom/fetch.ts b/src/internal/observable/dom/fetch.ts index bc047088234..cb10019dc1c 100644 --- a/src/internal/observable/dom/fetch.ts +++ b/src/internal/observable/dom/fetch.ts @@ -26,33 +26,34 @@ export function fromFetch(input: string | Request, init?: RequestInit): Observab * `fetch`. If the provided `signal` aborts, the error that `fetch` normally rejects with * in that scenario will be emitted as an error from the observable. * + * ## Examples + * * ### Basic Use * * ```ts - * import { of } from 'rxjs'; * import { fromFetch } from 'rxjs/fetch'; - * import { switchMap, catchError } from 'rxjs/operators'; + * import { switchMap, of, catchError } from 'rxjs'; * * const data$ = fromFetch('https://api.github.com/users?per_page=5').pipe( - * switchMap(response => { - * if (response.ok) { - * // OK return data - * return response.json(); - * } else { - * // Server is returning a status requiring the client to try something else. - * return of({ error: true, message: `Error ${response.status}` }); - * } - * }), - * catchError(err => { - * // Network or other error, handle appropriately - * console.error(err); - * return of({ error: true, message: err.message }) - * }) + * switchMap(response => { + * if (response.ok) { + * // OK return data + * return response.json(); + * } else { + * // Server is returning a status requiring the client to try something else. + * return of({ error: true, message: `Error ${ response.status }` }); + * } + * }), + * catchError(err => { + * // Network or other error, handle appropriately + * console.error(err); + * return of({ error: true, message: err.message }) + * }) * ); * * data$.subscribe({ - * next: result => console.log(result), - * complete: () => console.log('done') + * next: result => console.log(result), + * complete: () => console.log('done') * }); * ``` * @@ -80,16 +81,16 @@ export function fromFetch(input: string | Request, init?: RequestInit): Observab * }); * * data$.subscribe({ - * next: result => console.log(result), - * complete: () => console.log('done') + * next: result => console.log(result), + * complete: () => console.log('done') * }); * ``` * * @param input The resource you would like to fetch. Can be a url or a request object. * @param initWithSelector A configuration object for the fetch. * [See MDN for more details](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) - * @returns An Observable, that when subscribed to performs an HTTP request using the native `fetch` - * function. The {@link Subscription} is tied to an `AbortController` for the the fetch. + * @returns An Observable, that when subscribed to, performs an HTTP request using the native `fetch` + * function. The {@link Subscription} is tied to an `AbortController` for the fetch. */ export function fromFetch( input: string | Request, @@ -98,7 +99,7 @@ export function fromFetch( } = {} ): Observable { const { selector, ...init } = initWithSelector; - return new Observable((subscriber) => { + return new Observable(subscriber => { // Our controller for aborting this fetch. // Any externally provided AbortSignal will have to call // abort on this controller when signaled, because the @@ -144,7 +145,7 @@ export function fromFetch( }; fetch(input, perSubscriberInit) - .then((response) => { + .then(response => { if (selector) { // If we have a selector function, use it to project our response. // Note that any error that comes from our selector will be diff --git a/src/internal/observable/dom/webSocket.ts b/src/internal/observable/dom/webSocket.ts index e11560748c6..491d5e5775f 100644 --- a/src/internal/observable/dom/webSocket.ts +++ b/src/internal/observable/dom/webSocket.ts @@ -82,22 +82,27 @@ import { WebSocketSubject, WebSocketSubjectConfig } from './WebSocketSubject'; * is not a `WebSocketSubject`, so calling `next` or `multiplex` again will fail. For pushing values to the * server, use root `WebSocketSubject`. * - * ### Examples - * #### Listening for messages from the server + * ## Examples + * + * Listening for messages from the server + * * ```ts - * import { webSocket } from "rxjs/webSocket"; - * const subject = webSocket("ws://localhost:8081"); - * - * subject.subscribe( - * msg => console.log('message received: ' + msg), // Called whenever there is a message from the server. - * err => console.log(err), // Called if at any point WebSocket API signals some kind of error. - * () => console.log('complete') // Called when connection is closed (for whatever reason). - * ); + * import { webSocket } from 'rxjs/webSocket'; + * + * const subject = webSocket('ws://localhost:8081'); + * + * subject.subscribe({ + * next: msg => console.log('message received: ' + msg), // Called whenever there is a message from the server. + * error: err => console.log(err), // Called if at any point WebSocket API signals some kind of error. + * complete: () => console.log('complete') // Called when connection is closed (for whatever reason). + * }); * ``` * - * #### Pushing messages to the server + * Pushing messages to the server + * * ```ts - * import { webSocket } from "rxjs/webSocket"; + * import { webSocket } from 'rxjs/webSocket'; + * * const subject = webSocket('ws://localhost:8081'); * * subject.subscribe(); @@ -113,20 +118,22 @@ import { WebSocketSubject, WebSocketSubjectConfig } from './WebSocketSubject'; * // Also closes the connection, but let's the server know that this closing is caused by some error. * ``` * - * #### Multiplexing WebSocket + * Multiplexing WebSocket + * * ```ts - * import { webSocket } from "rxjs/webSocket"; + * import { webSocket } from 'rxjs/webSocket'; + * * const subject = webSocket('ws://localhost:8081'); * * const observableA = subject.multiplex( - * () => ({subscribe: 'A'}), // When server gets this message, it will start sending messages for 'A'... - * () => ({unsubscribe: 'A'}), // ...and when gets this one, it will stop. + * () => ({ subscribe: 'A' }), // When server gets this message, it will start sending messages for 'A'... + * () => ({ unsubscribe: 'A' }), // ...and when gets this one, it will stop. * message => message.type === 'A' // If the function returns `true` message is passed down the stream. Skipped if the function returns false. * ); * * const observableB = subject.multiplex( // And the same goes for 'B'. - * () => ({subscribe: 'B'}), - * () => ({unsubscribe: 'B'}), + * () => ({ subscribe: 'B' }), + * () => ({ unsubscribe: 'B' }), * message => message.type === 'B' * ); * diff --git a/src/internal/observable/empty.ts b/src/internal/observable/empty.ts index 14edd1a2b91..d097b88b448 100644 --- a/src/internal/observable/empty.ts +++ b/src/internal/observable/empty.ts @@ -11,7 +11,7 @@ import { SchedulerLike } from '../types'; * * ## Examples * - * ### Log complete notification + * Log complete notification * * ```ts * import { EMPTY } from 'rxjs'; @@ -25,7 +25,7 @@ import { SchedulerLike } from '../types'; * // Complete! * ``` */ -export const EMPTY = new Observable((subscriber) => subscriber.complete()); +export const EMPTY = new Observable(subscriber => subscriber.complete()); /** * Creates an Observable that emits no items to the Observer and immediately @@ -41,11 +41,10 @@ export const EMPTY = new Observable((subscriber) => subscriber.complete() * * ## Examples * - * ### Emit the number 7, then complete + * Emit the number 7, then complete * * ```ts - * import { empty } from 'rxjs'; - * import { startWith } from 'rxjs/operators'; + * import { empty, startWith } from 'rxjs'; * * const result = empty().pipe(startWith(7)); * result.subscribe(x => console.log(x)); @@ -54,11 +53,10 @@ export const EMPTY = new Observable((subscriber) => subscriber.complete() * // 7 * ``` * - * ### Map and flatten only odd numbers to the sequence 'a', 'b', 'c' + * Map and flatten only odd numbers to the sequence 'a', 'b', 'c' * * ```ts - * import { empty, interval, of } from 'rxjs'; - * import { mergeMap } from 'rxjs/operators'; + * import { interval, mergeMap, of, empty } from 'rxjs'; * * const interval$ = interval(1000); * const result = interval$.pipe( @@ -89,5 +87,5 @@ export function empty(scheduler?: SchedulerLike) { } function emptyScheduled(scheduler: SchedulerLike) { - return new Observable((subscriber) => scheduler.schedule(() => subscriber.complete())); + return new Observable(subscriber => scheduler.schedule(() => subscriber.complete())); } diff --git a/src/internal/observable/forkJoin.ts b/src/internal/observable/forkJoin.ts index ab5a5a19e99..33da7dc54c1 100644 --- a/src/internal/observable/forkJoin.ts +++ b/src/internal/observable/forkJoin.ts @@ -94,7 +94,8 @@ export function forkJoin>>( * * ## Examples * - * ### Use forkJoin with a dictionary of observable inputs + * Use `forkJoin` with a dictionary of observable inputs + * * ```ts * import { forkJoin, of, timer } from 'rxjs'; * @@ -110,10 +111,11 @@ export function forkJoin>>( * * // Logs: * // { foo: 4, bar: 8, baz: 0 } after 4 seconds - * // "This is how it ends!" immediately after + * // 'This is how it ends!' immediately after * ``` * - * ### Use forkJoin with an array of observable inputs + * Use `forkJoin` with an array of observable inputs + * * ```ts * import { forkJoin, of, timer } from 'rxjs'; * @@ -129,7 +131,7 @@ export function forkJoin>>( * * // Logs: * // [4, 8, 0] after 4 seconds - * // "This is how it ends!" immediately after + * // 'This is how it ends!' immediately after * ``` * * @see {@link combineLatest} @@ -145,7 +147,7 @@ export function forkJoin>>( export function forkJoin(...args: any[]): Observable { const resultSelector = popResultSelector(args); const { args: sources, keys } = argsArgArrayOrObject(args); - const result = new Observable((subscriber) => { + const result = new Observable(subscriber => { const { length } = sources; if (!length) { subscriber.complete(); @@ -159,7 +161,7 @@ export function forkJoin(...args: any[]): Observable { innerFrom(sources[sourceIndex]).subscribe( new OperatorSubscriber( subscriber, - (value) => { + value => { if (!hasValue) { hasValue = true; remainingEmissions--; diff --git a/src/internal/observable/from.ts b/src/internal/observable/from.ts index 1bbea4dd923..88b988724ab 100644 --- a/src/internal/observable/from.ts +++ b/src/internal/observable/from.ts @@ -22,7 +22,7 @@ export function from>(input: O, scheduler: Schedu * * ## Examples * - * ### Converts an array to an Observable + * Converts an array to an Observable * * ```ts * import { from } from 'rxjs'; @@ -38,13 +38,10 @@ export function from>(input: O, scheduler: Schedu * // 30 * ``` * - * --- - * - * ### Convert an infinite iterable (from a generator) to an Observable + * Convert an infinite iterable (from a generator) to an Observable * * ```ts - * import { from } from 'rxjs'; - * import { take } from 'rxjs/operators'; + * import { from, take } from 'rxjs'; * * function* generateDoubles(seed) { * let i = seed; @@ -72,9 +69,7 @@ export function from>(input: O, scheduler: Schedu * // 1536 * ``` * - * --- - * - * ### With async scheduler + * With `asyncScheduler` * * ```ts * import { from, asyncScheduler } from 'rxjs'; diff --git a/src/internal/observable/fromEvent.ts b/src/internal/observable/fromEvent.ts index 8044ff9da99..83a8ea802c6 100644 --- a/src/internal/observable/fromEvent.ts +++ b/src/internal/observable/fromEvent.ts @@ -185,7 +185,9 @@ export function fromEvent( * * * ## Examples - * ### Emits clicks happening on the DOM document + * + * Emit clicks happening on the DOM document + * * ```ts * import { fromEvent } from 'rxjs'; * @@ -197,7 +199,8 @@ export function fromEvent( * // occurs on the document. * ``` * - * ### Use addEventListener with capture option + * Use `addEventListener` with capture option + * * ```ts * import { fromEvent } from 'rxjs'; * @@ -251,7 +254,7 @@ export function fromEvent( const [add, remove] = // If it is an EventTarget, we need to use a slightly different method than the other two patterns. isEventTarget(target) - ? eventTargetMethods.map((methodName) => (handler: any) => target[methodName](eventName, handler, options as EventListenerOptions)) + ? eventTargetMethods.map(methodName => (handler: any) => target[methodName](eventName, handler, options as EventListenerOptions)) : // In all other cases, the call pattern is identical with the exception of the method names. isNodeStyleEventEmitter(target) ? nodeEventEmitterMethods.map(toCommonHandlerRegistry(target, eventName)) @@ -278,7 +281,7 @@ export function fromEvent( throw new TypeError('Invalid event target'); } - return new Observable((subscriber) => { + return new Observable(subscriber => { // The handler we are going to register. Forwards the event object, by itself, or // an array of arguments to the event handler, if there is more than one argument, // to the consumer. diff --git a/src/internal/observable/fromEventPattern.ts b/src/internal/observable/fromEventPattern.ts index 92f5e45ab08..0f15e405475 100644 --- a/src/internal/observable/fromEventPattern.ts +++ b/src/internal/observable/fromEventPattern.ts @@ -60,8 +60,9 @@ export function fromEventPattern( * that default project can be thought of as function that takes its first parameter * and ignores the rest. * - * ## Example - * ### Emits clicks happening on the DOM document + * ## Examples + * + * Emits clicks happening on the DOM document * * ```ts * import { fromEventPattern } from 'rxjs'; @@ -84,8 +85,7 @@ export function fromEventPattern( * // object will be logged. * ``` * - * ## Example - * ### Use with API that returns cancellation token + * Use with API that returns cancellation token * * ```ts * import { fromEventPattern } from 'rxjs'; @@ -100,8 +100,7 @@ export function fromEventPattern( * ); * ``` * - * ## Example - * ### Use with project function + * Use with project function * * ```ts * import { fromEventPattern } from 'rxjs'; @@ -148,7 +147,7 @@ export function fromEventPattern( return fromEventPattern(addHandler, removeHandler).pipe(mapOneOrManyArgs(resultSelector)); } - return new Observable((subscriber) => { + return new Observable(subscriber => { const handler = (...e: T[]) => subscriber.next(e.length === 1 ? e[0] : e); const retValue = addHandler(handler); return isFunction(removeHandler) ? () => removeHandler(handler, retValue) : undefined; diff --git a/src/internal/observable/generate.ts b/src/internal/observable/generate.ts index ed467e07031..d3245ad729b 100644 --- a/src/internal/observable/generate.ts +++ b/src/internal/observable/generate.ts @@ -47,7 +47,7 @@ export interface GenerateOptions extends GenerateBaseOptions { * * ## Examples * - * ### Produces sequences of number + * Produces sequence of numbers * * ```ts * import { generate } from 'rxjs'; @@ -62,12 +62,12 @@ export interface GenerateOptions extends GenerateBaseOptions { * // 2 * ``` * - * ### Use asap scheduler + * Use `asapScheduler` * * ```ts - * import { generate } from 'rxjs'; + * import { generate, asapScheduler } from 'rxjs'; * - * const result = generate(1, x => x < 5, x => x * 2, x => x + 1, asap); + * const result = generate(1, x => x < 5, x => x * 2, x => x + 1, asapScheduler); * * result.subscribe(x => console.log(x)); * @@ -142,7 +142,7 @@ export function generate( * * ## Examples * - * ### Use with condition and iterate functions + * Use with condition and iterate functions * * ```ts * import { generate } from 'rxjs'; @@ -158,10 +158,10 @@ export function generate( * // 0 * // 1 * // 2 - * // "Complete!" + * // 'Complete!' * ``` * - * ### Use with condition, iterate and resultSelector functions + * Use with condition, iterate and resultSelector functions * * ```ts * import { generate } from 'rxjs'; @@ -170,17 +170,17 @@ export function generate( * * result.subscribe({ * next: value => console.log(value), - * complete: () => console.log('complete!') + * complete: () => console.log('Complete!') * }); * * // Logs: * // 0 * // 1000 * // 2000 - * // "complete!" + * // 'Complete!' * ``` * - * ### Use with options object + * Use with options object * * ```ts * import { generate } from 'rxjs'; @@ -194,17 +194,17 @@ export function generate( * * result.subscribe({ * next: value => console.log(value), - * complete: () => console.log('complete!') + * complete: () => console.log('Complete!') * }); * * // Logs: * // 0 * // 1000 * // 2000 - * // "Complete!" + * // 'Complete!' * ``` * - * ### Use options object without condition function + * Use options object without condition function * * ```ts * import { generate } from 'rxjs'; @@ -217,7 +217,7 @@ export function generate( * * result.subscribe({ * next: value => console.log(value), - * complete: () => console.log('complete!') // This will never run + * complete: () => console.log('Complete!') // This will never run * }); * * // Logs: @@ -229,7 +229,6 @@ export function generate( * ``` * * @see {@link from} - * @see {@link index/Observable.create} * * @param {S} initialState Initial state. * @param {function (state: S): boolean} condition Condition to terminate generation (upon returning false). @@ -257,7 +256,7 @@ export function generate( * * ## Examples * - * ### Use options object with condition function + * Use options object with condition function * * ```ts * import { generate } from 'rxjs'; @@ -270,14 +269,14 @@ export function generate( * * result.subscribe({ * next: value => console.log(value), - * complete: () => console.log('complete!') + * complete: () => console.log('Complete!') * }); * * // Logs: * // 0 * // 1 * // 2 - * // "Complete!". + * // 'Complete!' * ``` * * @see {@link from} @@ -299,7 +298,7 @@ export function generate(options: GenerateBaseOptions): Observable; * * ## Examples * - * ### Use options object with condition and iterate function + * Use options object with condition and iterate function * * ```ts * import { generate } from 'rxjs'; @@ -313,14 +312,14 @@ export function generate(options: GenerateBaseOptions): Observable; * * result.subscribe({ * next: value => console.log(value), - * complete: () => console.log('complete!') + * complete: () => console.log('Complete!') * }); * * // Logs: * // 0 * // 1 * // 2 - * // "Complete!". + * // 'Complete!' * ``` * * @see {@link from} diff --git a/src/internal/observable/iif.ts b/src/internal/observable/iif.ts index d1e8e6544a2..631911b3eeb 100644 --- a/src/internal/observable/iif.ts +++ b/src/internal/observable/iif.ts @@ -16,7 +16,7 @@ import { ObservableInput } from '../types'; * * ## Examples * - * ### Change at runtime which Observable will be subscribed + * Change at runtime which Observable will be subscribed * * ```ts * import { iif, of } from 'rxjs'; @@ -32,45 +32,45 @@ import { ObservableInput } from '../types'; * firstOrSecond.subscribe(value => console.log(value)); * * // Logs: - * // "first" + * // 'first' * * subscribeToFirst = false; * firstOrSecond.subscribe(value => console.log(value)); * * // Logs: - * // "second" - * + * // 'second' * ``` * - * ### Control an access to an Observable + * Control access to an Observable * * ```ts + * import { iif, of, EMPTY } from 'rxjs'; + * * let accessGranted; * const observableIfYouHaveAccess = iif( * () => accessGranted, - * of('It seems you have an access...'), // Note that only one Observable is passed to the operator. + * of('It seems you have an access...'), + * EMPTY * ); * * accessGranted = true; - * observableIfYouHaveAccess.subscribe( - * value => console.log(value), - * err => {}, - * () => console.log('The end'), - * ); + * observableIfYouHaveAccess.subscribe({ + * next: value => console.log(value), + * complete: () => console.log('The end') + * }); * * // Logs: - * // "It seems you have an access..." - * // "The end" + * // 'It seems you have an access...' + * // 'The end' * * accessGranted = false; - * observableIfYouHaveAccess.subscribe( - * value => console.log(value), - * err => {}, - * () => console.log('The end'), - * ); + * observableIfYouHaveAccess.subscribe({ + * next: value => console.log(value), + * complete: () => console.log('The end') + * }); * * // Logs: - * // "The end" + * // 'The end' * ``` * * @see {@link defer} diff --git a/src/internal/observable/interval.ts b/src/internal/observable/interval.ts index 9b195134bd2..fc1b3e0a77c 100644 --- a/src/internal/observable/interval.ts +++ b/src/internal/observable/interval.ts @@ -7,8 +7,7 @@ import { timer } from './timer'; * Creates an Observable that emits sequential numbers every specified * interval of time, on a specified {@link SchedulerLike}. * - * Emits incremental numbers periodically in time. - * + * Emits incremental numbers periodically in time. * * ![](interval.png) * @@ -20,10 +19,11 @@ import { timer } from './timer'; * {@link SchedulerLike} to it. * * ## Example + * * Emits ascending numbers, one every second (1000ms) up to the number 3 + * * ```ts - * import { interval } from 'rxjs'; - * import { take } from 'rxjs/operators'; + * import { interval, take } from 'rxjs'; * * const numbers = interval(1000); * diff --git a/src/internal/observable/merge.ts b/src/internal/observable/merge.ts index 268c03363b1..38adf345dc5 100644 --- a/src/internal/observable/merge.ts +++ b/src/internal/observable/merge.ts @@ -33,7 +33,9 @@ export function merge( * Observable will be immediately emitted on the output Observable. * * ## Examples - * ### Merge together two Observables: 1s interval and clicks + * + * Merge together two Observables: 1s interval and clicks + * * ```ts * import { merge, fromEvent, interval } from 'rxjs'; * @@ -49,14 +51,15 @@ export function merge( * // as they occur. * ``` * - * ### Merge together 3 Observables, but only 2 run concurrently + * Merge together 3 Observables, but run only 2 concurrently + * * ```ts - * import { merge, interval } from 'rxjs'; - * import { take } from 'rxjs/operators'; + * import { interval, take, merge } from 'rxjs'; * * const timer1 = interval(1000).pipe(take(10)); * const timer2 = interval(2000).pipe(take(6)); * const timer3 = interval(500).pipe(take(10)); + * * const concurrent = 2; // the argument * const merged = merge(timer1, timer2, timer3, concurrent); * merged.subscribe(x => console.log(x)); diff --git a/src/internal/observable/never.ts b/src/internal/observable/never.ts index ead9ba1895d..cfbec7de944 100644 --- a/src/internal/observable/never.ts +++ b/src/internal/observable/never.ts @@ -13,21 +13,24 @@ import { noop } from '../util/noop'; * Subscriptions need to be manually disposed. * * ## Example - * ### Emit the number 7, then never emit anything else (not even complete) + * + * Emit the number 7, then never emit anything else (not even complete) + * * ```ts - * import { NEVER } from 'rxjs'; - * import { startWith } from 'rxjs/operators'; + * import { NEVER, startWith } from 'rxjs'; * - * function info() { - * console.log('Will not be called'); - * } - * const result = NEVER.pipe(startWith(7)); - * result.subscribe(x => console.log(x), info, info); + * const info = () => console.log('Will not be called'); * + * const result = NEVER.pipe(startWith(7)); + * result.subscribe({ + * next: x => console.log(x), + * error: info, + * complete: info + * }); * ``` * * @see {@link Observable} - * @see {@link index/EMPTY} + * @see {@link EMPTY} * @see {@link of} * @see {@link throwError} */ diff --git a/src/internal/observable/of.ts b/src/internal/observable/of.ts index 7f9fe21380d..dc0c918236b 100644 --- a/src/internal/observable/of.ts +++ b/src/internal/observable/of.ts @@ -40,11 +40,11 @@ export function of(...values: A): Observable console.log('next:', next), - * err => console.log('error:', err), - * () => console.log('the end'), - * ); + * .subscribe({ + * next: value => console.log('next:', value), + * error: err => console.log('error:', err), + * complete: () => console.log('the end'), + * }); * * // Outputs * // next: 10 @@ -59,11 +59,11 @@ export function of(...values: A): Observable console.log('next:', next), - * err => console.log('error:', err), - * () => console.log('the end'), - * ); + * .subscribe({ + * next: value => console.log('next:', value), + * error: err => console.log('error:', err), + * complete: () => console.log('the end'), + * }); * * // Outputs * // next: [1, 2, 3] diff --git a/src/internal/observable/onErrorResumeNext.ts b/src/internal/observable/onErrorResumeNext.ts index fe945c26b29..60fbceca396 100644 --- a/src/internal/observable/onErrorResumeNext.ts +++ b/src/internal/observable/onErrorResumeNext.ts @@ -11,18 +11,18 @@ export function onErrorResumeNext(...sources: [... /* tslint:enable:max-line-length */ /** - * When any of the provided Observable emits an complete or error notification, it immediately subscribes to the next one + * When any of the provided Observable emits a complete or an error notification, it immediately subscribes to the next one * that was passed. * * Execute series of Observables no matter what, even if it means swallowing errors. * * ![](onErrorResumeNext.png) * - * `onErrorResumeNext` Will subscribe to each observable source it is provided, in order. + * `onErrorResumeNext` will subscribe to each observable source it is provided, in order. * If the source it's subscribed to emits an error or completes, it will move to the next source * without error. * - * If `onErrorResumeNext` is provided no arguments, or a single, empty array, it will return {@link index/EMPTY}. + * If `onErrorResumeNext` is provided no arguments, or a single, empty array, it will return {@link EMPTY}. * * `onErrorResumeNext` is basically {@link concat}, only it will continue, even if one of its * sources emits an error. @@ -32,25 +32,28 @@ export function onErrorResumeNext(...sources: [... * always use the {@link catchError} operator on them before passing them into `onErrorResumeNext`. * * ## Example - * Subscribe to the next Observable after map fails + * + * Subscribe to the next Observable after map fails + * * ```ts - * import { onErrorResumeNext, of } from 'rxjs'; - * import { map } from 'rxjs/operators'; + * import { onErrorResumeNext, of, map } from 'rxjs'; * * onErrorResumeNext( - * of(1, 2, 3, 0).pipe( - * map(x => { - * if (x === 0) throw Error(); - * return 10 / x; - * }) - * ), - * of(1, 2, 3), + * of(1, 2, 3, 0).pipe( + * map(x => { + * if (x === 0) { + * throw Error(); + * } + * return 10 / x; + * }) + * ), + * of(1, 2, 3) * ) - * .subscribe( - * val => console.log(val), - * err => console.log(err), // Will never be called. - * () => console.log('done'), - * ); + * .subscribe({ + * next: value => console.log(value), + * error: err => console.log(err), // Will never be called. + * complete: () => console.log('done') + * }); * * // Logs: * // 10 @@ -59,7 +62,7 @@ export function onErrorResumeNext(...sources: [... * // 1 * // 2 * // 3 - * // "done" + * // 'done' * ``` * * @see {@link concat} diff --git a/src/internal/observable/pairs.ts b/src/internal/observable/pairs.ts index 071879bce88..4dafb9ffb83 100644 --- a/src/internal/observable/pairs.ts +++ b/src/internal/observable/pairs.ts @@ -36,11 +36,13 @@ export function pairs( * enumerable keys that are present on an object directly - not ones inherited * via prototype chain. * - * By default these arrays are emitted synchronously. To change that you can + * By default, these arrays are emitted synchronously. To change that you can * pass a {@link SchedulerLike} as a second argument to `pairs`. * * ## Example - * ### Converts an object to an Observable + * + * Converts an object to an Observable + * * ```ts * import { pairs } from 'rxjs'; * @@ -56,10 +58,10 @@ export function pairs( * }); * * // Logs: - * // ["foo", 42], - * // ["bar", 56], - * // ["baz", 78], - * // "Complete!" + * // ['foo', 42] + * // ['bar', 56] + * // ['baz', 78] + * // 'Complete!' * ``` * * ### Object.entries required diff --git a/src/internal/observable/partition.ts b/src/internal/observable/partition.ts index 1c3c9dfa9b5..d69db663f55 100644 --- a/src/internal/observable/partition.ts +++ b/src/internal/observable/partition.ts @@ -41,12 +41,14 @@ export function partition(source: ObservableInput, predicate: (value: T, i * behaves like {@link filter} with the predicate negated. * * ## Example + * * Partition a set of numbers into odds and evens observables + * * ```ts * import { of, partition } from 'rxjs'; * * const observableValues = of(1, 2, 3, 4, 5, 6); - * const [evens$, odds$] = partition(observableValues, (value, index) => value % 2 === 0); + * const [evens$, odds$] = partition(observableValues, value => value % 2 === 0); * * odds$.subscribe(x => console.log('odds', x)); * evens$.subscribe(x => console.log('evens', x)); diff --git a/src/internal/observable/race.ts b/src/internal/observable/race.ts index 2093ad926e7..cc860202e13 100644 --- a/src/internal/observable/race.ts +++ b/src/internal/observable/race.ts @@ -28,20 +28,18 @@ export function race(...inputs: [...ObservableInpu * input. * * ## Example - * ### Subscribes to the observable that was the first to start emitting. + * + * Subscribes to the observable that was the first to start emitting. * * ```ts - * import { race, interval } from 'rxjs'; - * import { mapTo } from 'rxjs/operators'; + * import { interval, map, race } from 'rxjs'; * - * const obs1 = interval(1000).pipe(mapTo('fast one')); - * const obs2 = interval(3000).pipe(mapTo('medium one')); - * const obs3 = interval(5000).pipe(mapTo('slow one')); + * const obs1 = interval(7000).pipe(map(() => 'slow one')); + * const obs2 = interval(3000).pipe(map(() => 'fast one')); + * const obs3 = interval(5000).pipe(map(() => 'medium one')); * - * race(obs3, obs1, obs2) - * .subscribe( - * winner => console.log(winner) - * ); + * race(obs1, obs2, obs3) + * .subscribe(winner => console.log(winner)); * * // Outputs * // a series of 'fast one' @@ -72,7 +70,7 @@ export function raceInit(sources: ObservableInput[]) { for (let i = 0; subscriptions && !subscriber.closed && i < sources.length; i++) { subscriptions.push( innerFrom(sources[i] as ObservableInput).subscribe( - new OperatorSubscriber(subscriber, (value) => { + new OperatorSubscriber(subscriber, value => { if (subscriptions) { // We're still racing, but we won! So unsubscribe // all other subscriptions that we have, except this one. diff --git a/src/internal/observable/range.ts b/src/internal/observable/range.ts index 834e393932f..b4860727068 100644 --- a/src/internal/observable/range.ts +++ b/src/internal/observable/range.ts @@ -24,7 +24,7 @@ export function range(start: number, count: number | undefined, scheduler: Sched * * ## Example * - * ### Produce a range of numbers + * Produce a range of numbers * * ```ts * import { range } from 'rxjs'; @@ -32,19 +32,19 @@ export function range(start: number, count: number | undefined, scheduler: Sched * const numbers = range(1, 3); * * numbers.subscribe({ - * next: value => { console.log(value) }, - * complete: () => { console.log('Complete!') } + * next: value => console.log(value), + * complete: () => console.log('Complete!') * }); * * // Logs: * // 1 * // 2 * // 3 - * // "Complete!" + * // 'Complete!' * ``` * * @see {@link timer} - * @see {@link index/interval} + * @see {@link interval} * * @param {number} [start=0] The value of the first integer in the sequence. * @param {number} count The number of sequential integers to generate. @@ -71,7 +71,7 @@ export function range(start: number, count?: number, scheduler?: SchedulerLike): return new Observable( scheduler ? // The deprecated scheduled path. - (subscriber) => { + subscriber => { let n = start; return scheduler.schedule(function () { if (n < end) { @@ -83,7 +83,7 @@ export function range(start: number, count?: number, scheduler?: SchedulerLike): }); } : // Standard synchronous range. - (subscriber) => { + subscriber => { let n = start; while (n < end && !subscriber.closed) { subscriber.next(n++); diff --git a/src/internal/observable/throwError.ts b/src/internal/observable/throwError.ts index 8faab39be44..8b5a6dadcf7 100644 --- a/src/internal/observable/throwError.ts +++ b/src/internal/observable/throwError.ts @@ -20,7 +20,7 @@ import { isFunction } from '../util/isFunction'; * ## Example * * Create a simple observable that will create a new error with a timestamp and log it - * and the message every time you subscribe to it. + * and the message every time you subscribe to it * * ```ts * import { throwError } from 'rxjs'; @@ -28,70 +28,68 @@ import { isFunction } from '../util/isFunction'; * let errorCount = 0; * * const errorWithTimestamp$ = throwError(() => { - * const error: any = new Error(`This is error number ${++errorCount}`); - * error.timestamp = Date.now(); - * return error; + * const error: any = new Error(`This is error number ${ ++errorCount }`); + * error.timestamp = Date.now(); + * return error; * }); * * errorWithTimestamp$.subscribe({ - * error: err => console.log(err.timestamp, err.message) + * error: err => console.log(err.timestamp, err.message) * }); * * errorWithTimestamp$.subscribe({ - * error: err => console.log(err.timestamp, err.message) + * error: err => console.log(err.timestamp, err.message) * }); * - * // Logs the timestamp and a new error message each subscription; + * // Logs the timestamp and a new error message for each subscription * ``` * * ## Unnecessary usage * * Using `throwError` inside of an operator or creation function - * with a callback, is usually not necessary: + * with a callback, is usually not necessary * * ```ts - * import { throwError, timer, of } from 'rxjs'; - * import { concatMap } from 'rxjs/operators'; + * import { of, concatMap, timer, throwError } from 'rxjs'; * * const delays$ = of(1000, 2000, Infinity, 3000); * * delays$.pipe( - * concatMap(ms => { - * if (ms < 10000) { - * return timer(ms); - * } else { - * // This is probably overkill. - * return throwError(() => new Error(`Invalid time ${ms}`)); - * } - * }) + * concatMap(ms => { + * if (ms < 10000) { + * return timer(ms); + * } else { + * // This is probably overkill. + * return throwError(() => new Error(`Invalid time ${ ms }`)); + * } + * }) * ) * .subscribe({ - * next: console.log, - * error: console.error + * next: console.log, + * error: console.error * }); * ``` * - * You can just throw the error instead: + * You can just throw the error instead * * ```ts - * import { throwError, timer, of } from 'rxjs'; - * import { concatMap } from 'rxjs/operators'; + * import { of, concatMap, timer } from 'rxjs'; * * const delays$ = of(1000, 2000, Infinity, 3000); * * delays$.pipe( - * concatMap(ms => { - * if (ms < 10000) { - * return timer(ms); - * } else { - * // Cleaner and easier to read for most folks. - * throw new Error(`Invalid time ${ms}`); - * } - * }) + * concatMap(ms => { + * if (ms < 10000) { + * return timer(ms); + * } else { + * // Cleaner and easier to read for most folks. + * throw new Error(`Invalid time ${ ms }`); + * } + * }) * ) * .subscribe({ - * next: console.log, - * error: console.error + * next: console.log, + * error: console.error * }); * ``` * @@ -123,5 +121,5 @@ export function throwError(errorOrErrorFactory: any, scheduler: SchedulerLike): export function throwError(errorOrErrorFactory: any, scheduler?: SchedulerLike): Observable { const errorFactory = isFunction(errorOrErrorFactory) ? errorOrErrorFactory : () => errorOrErrorFactory; const init = (subscriber: Subscriber) => subscriber.error(errorFactory()); - return new Observable(scheduler ? (subscriber) => scheduler.schedule(init as any, 0, subscriber) : init); + return new Observable(scheduler ? subscriber => scheduler.schedule(init as any, 0, subscriber) : init); } diff --git a/src/internal/observable/timer.ts b/src/internal/observable/timer.ts index 361e7730d91..9d22289ab29 100644 --- a/src/internal/observable/timer.ts +++ b/src/internal/observable/timer.ts @@ -26,19 +26,17 @@ import { isValidDate } from '../util/isDate'; * a few seconds and start a subscription to a source. * * ```ts - * import { timer, of } from 'rxjs'; - * import { concatMapTo } from 'rxjs/operators'; + * import { of, timer, concatMap } from 'rxjs'; * * // This could be any observable * const source = of(1, 2, 3); * - * const result = timer(3000).pipe( - * concatMapTo(source) - * ) - * .subscribe(console.log); + * timer(3000) + * .pipe(concatMap(() => source)) + * .subscribe(console.log); * ``` * - * ### Take all of the values until the start of the next minute + * ### Take all values until the start of the next minute * * Using a `Date` as the trigger for the first emission, you can * do things like wait until midnight to fire an event, or in this case, @@ -47,8 +45,7 @@ import { isValidDate } from '../util/isDate'; * {@link takeUntil}. * * ```ts - * import { interval, timer } from 'rxjs'; - * import { takeUntil } from 'rxjs/operators'; + * import { interval, takeUntil, timer } from 'rxjs'; * * // Build a Date object that marks the * // next minute. @@ -58,8 +55,8 @@ import { isValidDate } from '../util/isDate'; * currentDate.getMonth(), * currentDate.getDate(), * currentDate.getHours(), - * currentDate.getMinutes() + 1, - * ) + * currentDate.getMinutes() + 1 + * ); * * // This could be any observable stream * const source = interval(1000); @@ -97,7 +94,7 @@ export function timer(due: number | Date, scheduler?: SchedulerLike): Observable * * ### Start an interval that starts right away * - * Since {@link index/interval} waits for the passed delay before starting, + * Since {@link interval} waits for the passed delay before starting, * sometimes that's not ideal. You may want to start an interval immediately. * `timer` works well for this. Here we have both side-by-side so you can * see them in comparison. @@ -155,7 +152,7 @@ export function timer( } } - return new Observable((subscriber) => { + return new Observable(subscriber => { // If a valid date is passed, calculate how long to wait before // executing the first value... otherwise, if it's a number just schedule // that many milliseconds (or scheduler-specified unit size) in the future. diff --git a/src/internal/observable/zip.ts b/src/internal/observable/zip.ts index 4301089cd4c..ea6f387fe5f 100644 --- a/src/internal/observable/zip.ts +++ b/src/internal/observable/zip.ts @@ -28,12 +28,11 @@ export function zip( * Combine age and name from different sources * * ```ts - * import { zip, of } from 'rxjs'; - * import { map } from 'rxjs/operators'; + * import { of, zip, map } from 'rxjs'; * - * let age$ = of(27, 25, 29); - * let name$ = of('Foo', 'Bar', 'Beer'); - * let isDev$ = of(true, true, false); + * const age$ = of(27, 25, 29); + * const name$ = of('Foo', 'Bar', 'Beer'); + * const isDev$ = of(true, true, false); * * zip(age$, name$, isDev$).pipe( * map(([age, name, isDev]) => ({ age, name, isDev })) @@ -45,6 +44,7 @@ export function zip( * // { age: 25, name: 'Bar', isDev: true } * // { age: 29, name: 'Beer', isDev: false } * ``` + * * @param sources * @return {Observable} */ @@ -54,7 +54,7 @@ export function zip(...args: unknown[]): Observable { const sources = argsOrArgArray(args) as Observable[]; return sources.length - ? new Observable((subscriber) => { + ? new Observable(subscriber => { // A collection of buffers of values from each source. // Keyed by the same index with which the sources were passed in. let buffers: unknown[][] = sources.map(() => []); @@ -76,13 +76,13 @@ export function zip(...args: unknown[]): Observable { innerFrom(sources[sourceIndex]).subscribe( new OperatorSubscriber( subscriber, - (value) => { + value => { buffers[sourceIndex].push(value); // if every buffer has at least one value in it, then we // can shift out the oldest value from each buffer and emit // them as an array. - if (buffers.every((buffer) => buffer.length)) { - const result: any = buffers.map((buffer) => buffer.shift()!); + if (buffers.every(buffer => buffer.length)) { + const result: any = buffers.map(buffer => buffer.shift()!); // Emit the array. If theres' a result selector, use that. subscriber.next(resultSelector ? resultSelector(...result) : result); // If any one of the sources is both complete and has an empty buffer diff --git a/src/internal/operators/audit.ts b/src/internal/operators/audit.ts index e8bdfa000f7..578a7aea9e0 100644 --- a/src/internal/operators/audit.ts +++ b/src/internal/operators/audit.ts @@ -29,14 +29,15 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * ## Example * * Emit clicks at a rate of at most one click per second + * * ```ts - * import { fromEvent, interval } from 'rxjs'; - * import { audit } from 'rxjs/operators' + * import { fromEvent, audit, interval } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const result = clicks.pipe(audit(ev => interval(1000))); * result.subscribe(x => console.log(x)); * ``` + * * @see {@link auditTime} * @see {@link debounce} * @see {@link delayWhen} @@ -76,7 +77,7 @@ export function audit(durationSelector: (value: T) => ObservableInput): source.subscribe( new OperatorSubscriber( subscriber, - (value) => { + value => { hasValue = true; lastValue = value; if (!durationSubscriber) { diff --git a/src/internal/operators/auditTime.ts b/src/internal/operators/auditTime.ts index 7777ddce18f..af83889db99 100644 --- a/src/internal/operators/auditTime.ts +++ b/src/internal/operators/auditTime.ts @@ -1,4 +1,4 @@ -import { async } from '../scheduler/async'; +import { asyncScheduler } from '../scheduler/async'; import { audit } from './audit'; import { timer } from '../observable/timer'; import { MonoTypeOperatorFunction, SchedulerLike } from '../types'; @@ -27,9 +27,9 @@ import { MonoTypeOperatorFunction, SchedulerLike } from '../types'; * ## Example * * Emit clicks at a rate of at most one click per second + * * ```ts - * import { fromEvent } from 'rxjs'; - * import { auditTime } from 'rxjs/operators'; + * import { fromEvent, auditTime } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const result = clicks.pipe(auditTime(1000)); @@ -50,6 +50,6 @@ import { MonoTypeOperatorFunction, SchedulerLike } from '../types'; * @return A function that returns an Observable that performs rate-limiting of * emissions from the source Observable. */ -export function auditTime(duration: number, scheduler: SchedulerLike = async): MonoTypeOperatorFunction { +export function auditTime(duration: number, scheduler: SchedulerLike = asyncScheduler): MonoTypeOperatorFunction { return audit(() => timer(duration, scheduler)); } diff --git a/src/internal/operators/buffer.ts b/src/internal/operators/buffer.ts index e7631aaecb6..8195259fbbf 100644 --- a/src/internal/operators/buffer.ts +++ b/src/internal/operators/buffer.ts @@ -22,8 +22,7 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * On every click, emit array of most recent interval events * * ```ts - * import { fromEvent, interval } from 'rxjs'; - * import { buffer } from 'rxjs/operators'; + * import { fromEvent, interval, buffer } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const intervalEvents = interval(1000); @@ -51,7 +50,7 @@ export function buffer(closingNotifier: Observable): OperatorFunction currentBuffer.push(value), + value => currentBuffer.push(value), () => { subscriber.next(currentBuffer); subscriber.complete(); diff --git a/src/internal/operators/bufferCount.ts b/src/internal/operators/bufferCount.ts index ee7bf6844aa..e4156480dd4 100644 --- a/src/internal/operators/bufferCount.ts +++ b/src/internal/operators/bufferCount.ts @@ -23,8 +23,7 @@ import { arrRemove } from '../util/arrRemove'; * Emit the last two click events as an array * * ```ts - * import { fromEvent } from 'rxjs'; - * import { bufferCount } from 'rxjs/operators'; + * import { fromEvent, bufferCount } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const buffered = clicks.pipe(bufferCount(2)); @@ -34,8 +33,7 @@ import { arrRemove } from '../util/arrRemove'; * On every click, emit the last two click events as an array * * ```ts - * import { fromEvent } from 'rxjs'; - * import { bufferCount } from 'rxjs/operators'; + * import { fromEvent, bufferCount } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const buffered = clicks.pipe(bufferCount(2, 1)); @@ -68,7 +66,7 @@ export function bufferCount(bufferSize: number, startBufferEvery: number | nu source.subscribe( new OperatorSubscriber( subscriber, - (value) => { + value => { let toEmit: T[][] | null = null; // Check to see if we need to start a buffer. diff --git a/src/internal/operators/bufferTime.ts b/src/internal/operators/bufferTime.ts index cab6dd2b21e..afc6c1d0450 100644 --- a/src/internal/operators/bufferTime.ts +++ b/src/internal/operators/bufferTime.ts @@ -44,8 +44,7 @@ export function bufferTime( * Every second, emit an array of the recent click events * * ```ts - * import { fromEvent } from 'rxjs'; - * import { bufferTime } from 'rxjs/operators'; + * import { fromEvent, bufferTime } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const buffered = clicks.pipe(bufferTime(1000)); @@ -55,8 +54,7 @@ export function bufferTime( * Every 5 seconds, emit the click events from the next 2 seconds * * ```ts - * import { fromEvent } from 'rxjs'; - * import { bufferTime } from 'rxjs/operators'; + * import { fromEvent, bufferTime } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const buffered = clicks.pipe(bufferTime(2000, 5000)); diff --git a/src/internal/operators/bufferToggle.ts b/src/internal/operators/bufferToggle.ts index 61d36135704..92ac935fbc2 100644 --- a/src/internal/operators/bufferToggle.ts +++ b/src/internal/operators/bufferToggle.ts @@ -20,14 +20,12 @@ import { arrRemove } from '../util/arrRemove'; * Observable provided to `openings`, and closing and sending the buffers when * a Subscribable or Promise returned by the `closingSelector` function emits. * - * * ## Example * * Every other second, emit the click events from the next 500ms * * ```ts - * import { fromEvent, interval, EMPTY } from 'rxjs'; - * import { bufferToggle } from 'rxjs/operators'; + * import { fromEvent, interval, bufferToggle, EMPTY } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const openings = interval(1000); @@ -62,7 +60,7 @@ export function bufferToggle( innerFrom(openings).subscribe( new OperatorSubscriber( subscriber, - (openValue) => { + openValue => { const buffer: T[] = []; buffers.push(buffer); // We use this composite subscription, so that @@ -85,7 +83,7 @@ export function bufferToggle( source.subscribe( new OperatorSubscriber( subscriber, - (value) => { + value => { // Value from our source. Add it to all pending buffers. for (const buffer of buffers) { buffer.push(value); diff --git a/src/internal/operators/bufferWhen.ts b/src/internal/operators/bufferWhen.ts index fd8638e09bb..78908b27c05 100644 --- a/src/internal/operators/bufferWhen.ts +++ b/src/internal/operators/bufferWhen.ts @@ -24,8 +24,7 @@ import { innerFrom } from '../observable/innerFrom'; * Emit an array of the last clicks every [1-5] random seconds * * ```ts - * import { fromEvent, interval } from 'rxjs'; - * import { bufferWhen } from 'rxjs/operators'; + * import { fromEvent, bufferWhen, interval } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const buffered = clicks.pipe(bufferWhen(() => @@ -34,7 +33,6 @@ import { innerFrom } from '../observable/innerFrom'; * buffered.subscribe(x => console.log(x)); * ``` * - * * @see {@link buffer} * @see {@link bufferCount} * @see {@link bufferTime} @@ -79,7 +77,7 @@ export function bufferWhen(closingSelector: () => ObservableInput): Oper new OperatorSubscriber( subscriber, // Add every new value to the current buffer. - (value) => buffer?.push(value), + value => buffer?.push(value), // When we complete, emit the buffer if we have one, // then complete the result. () => { diff --git a/src/internal/operators/catchError.ts b/src/internal/operators/catchError.ts index 7a69d49774a..38752b7eee4 100644 --- a/src/internal/operators/catchError.ts +++ b/src/internal/operators/catchError.ts @@ -28,20 +28,21 @@ export function catchError>( * subscribe to it, and forward all of its events to the resulting observable. * * ## Examples + * * Continues with a different Observable when there's an error * * ```ts - * import { of } from 'rxjs'; - * import { map, catchError } from 'rxjs/operators'; + * import { of, map, catchError } from 'rxjs'; * - * of(1, 2, 3, 4, 5).pipe( + * of(1, 2, 3, 4, 5) + * .pipe( * map(n => { - * if (n === 4) { - * throw 'four!'; + * if (n === 4) { + * throw 'four!'; * } - * return n; + * return n; * }), - * catchError(err => of('I', 'II', 'III', 'IV', 'V')), + * catchError(err => of('I', 'II', 'III', 'IV', 'V')) * ) * .subscribe(x => console.log(x)); * // 1, 2, 3, I, II, III, IV, V @@ -50,18 +51,18 @@ export function catchError>( * Retries the caught source Observable again in case of error, similar to retry() operator * * ```ts - * import { of } from 'rxjs'; - * import { map, catchError, take } from 'rxjs/operators'; + * import { of, map, catchError, take } from 'rxjs'; * - * of(1, 2, 3, 4, 5).pipe( + * of(1, 2, 3, 4, 5) + * .pipe( * map(n => { - * if (n === 4) { - * throw 'four!'; + * if (n === 4) { + * throw 'four!'; * } - * return n; + * return n; * }), * catchError((err, caught) => caught), - * take(30), + * take(30) * ) * .subscribe(x => console.log(x)); * // 1, 2, 3, 1, 2, 3, ... @@ -70,10 +71,10 @@ export function catchError>( * Throws a new error when the source Observable throws an error * * ```ts - * import { of } from 'rxjs'; - * import { map, catchError } from 'rxjs/operators'; + * import { of, map, catchError } from 'rxjs'; * - * of(1, 2, 3, 4, 5).pipe( + * of(1, 2, 3, 4, 5) + * .pipe( * map(n => { * if (n === 4) { * throw 'four!'; @@ -82,12 +83,12 @@ export function catchError>( * }), * catchError(err => { * throw 'error in source. Details: ' + err; - * }), + * }) * ) - * .subscribe( - * x => console.log(x), - * err => console.log(err) - * ); + * .subscribe({ + * next: x => console.log(x), + * error: err => console.log(err) + * }); * // 1, 2, 3, error in source. Details: four! * ``` * @@ -112,7 +113,7 @@ export function catchError>( let handledResult: Observable>; innerSub = source.subscribe( - new OperatorSubscriber(subscriber, undefined, undefined, (err) => { + new OperatorSubscriber(subscriber, undefined, undefined, err => { handledResult = innerFrom(selector(err, catchError(selector)(source))); if (innerSub) { innerSub.unsubscribe(); diff --git a/src/internal/operators/combineLatestAll.ts b/src/internal/operators/combineLatestAll.ts index 7d06b87bccb..ebedee6ea61 100644 --- a/src/internal/operators/combineLatestAll.ts +++ b/src/internal/operators/combineLatestAll.ts @@ -13,7 +13,7 @@ export function combineLatestAll(project: (...values: Array) => R): Oper * ![](combineLatestAll.png) * * `combineLatestAll` takes an Observable of Observables, and collects all Observables from it. Once the outer Observable completes, - * it subscribes to all collected Observables and combines their values using the {@link combineLatest} strategy, such that: + * it subscribes to all collected Observables and combines their values using the {@link combineLatest} strategy, such that: * * * Every time an inner Observable emits, the output Observable emits * * When the returned observable emits, it emits all of the latest values by: @@ -21,26 +21,19 @@ export function combineLatestAll(project: (...values: Array) => R): Oper * arrived, and the result of the `project` function is what is emitted by the output Observable. * * If there is no `project` function, an array of all the most recent values is emitted by the output Observable. * - * --- + * ## Example * - * ## Examples - * - * ### Map two click events to a finite interval Observable, then apply `combineLatestAll` + * Map two click events to a finite interval Observable, then apply `combineLatestAll` * * ```ts - * import { fromEvent, interval } from 'rxjs'; - * import { map, combineLatestAll, take } from 'rxjs/operators'; + * import { fromEvent, map, interval, take, combineLatestAll } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const higherOrder = clicks.pipe( - * map(ev => - * interval(Math.random() * 2000).pipe(take(3)) - * ), + * map(ev => interval(Math.random() * 2000).pipe(take(3))), * take(2) * ); - * const result = higherOrder.pipe( - * combineLatestAll() - * ); + * const result = higherOrder.pipe(combineLatestAll()); * * result.subscribe(x => console.log(x)); * ``` diff --git a/src/internal/operators/combineLatestWith.ts b/src/internal/operators/combineLatestWith.ts index 7a6b177dadb..b262f890b8a 100644 --- a/src/internal/operators/combineLatestWith.ts +++ b/src/internal/operators/combineLatestWith.ts @@ -12,13 +12,12 @@ import { combineLatest } from './combineLatest'; * * This is a useful operator for eagerly calculating values based off of changed inputs. * - * ### Example + * ## Example * - * Simple calculation from two inputs. + * Simple concatenation of values from two inputs * * ```ts - * import { fromEvent } from 'rxjs'; - * import { map, combineLatestWith } from 'rxjs/operators'; + * import { fromEvent, combineLatestWith, map } from 'rxjs'; * * // Setup: Add two inputs to the page * const input1 = document.createElement('input'); @@ -33,11 +32,11 @@ import { combineLatest } from './combineLatest'; * // Combine the changes by adding them together * input1Changes$.pipe( * combineLatestWith(input2Changes$), - * map(([e1, e2]) => Number(e1.target.value) + Number(e2.target.value)), + * map(([e1, e2]) => (e1.target).value + ' - ' + (e2.target).value) * ) * .subscribe(x => console.log(x)); - * * ``` + * * @param otherSources the other sources to subscribe to. * @return A function that returns an Observable that emits the latest * emissions from both source and provided Observables. diff --git a/src/internal/operators/concatAll.ts b/src/internal/operators/concatAll.ts index 727b7f1bd31..ff37a6f5e59 100644 --- a/src/internal/operators/concatAll.ts +++ b/src/internal/operators/concatAll.ts @@ -26,13 +26,13 @@ import { OperatorFunction, ObservableInput, ObservedValueOf } from '../types'; * ## Example * * For each click event, tick every second from 0 to 3, with no concurrency + * * ```ts - * import { fromEvent, interval } from 'rxjs'; - * import { map, take, concatAll } from 'rxjs/operators'; + * import { fromEvent, map, interval, take, concatAll } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const higherOrder = clicks.pipe( - * map(ev => interval(1000).pipe(take(4))), + * map(ev => interval(1000).pipe(take(4))) * ); * const firstOrder = higherOrder.pipe(concatAll()); * firstOrder.subscribe(x => console.log(x)); diff --git a/src/internal/operators/concatMap.ts b/src/internal/operators/concatMap.ts index 7dfbac5bcfa..21bbf424319 100644 --- a/src/internal/operators/concatMap.ts +++ b/src/internal/operators/concatMap.ts @@ -42,11 +42,11 @@ export function concatMap>( * to `1`. * * ## Example + * * For each click event, tick every second from 0 to 3, with no concurrency * * ```ts - * import { fromEvent, interval } from 'rxjs'; - * import { concatMap, take } from 'rxjs/operators'; + * import { fromEvent, concatMap, interval, take } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const result = clicks.pipe( diff --git a/src/internal/operators/concatMapTo.ts b/src/internal/operators/concatMapTo.ts index e0142721dcd..0fd8b253a95 100644 --- a/src/internal/operators/concatMapTo.ts +++ b/src/internal/operators/concatMapTo.ts @@ -40,14 +40,15 @@ export function concatMapTo>( * set to `1`. * * ## Example + * * For each click event, tick every second from 0 to 3, with no concurrency + * * ```ts - * import { fromEvent, interval } from 'rxjs'; - * import { concatMapTo, take } from 'rxjs/operators'; + * import { fromEvent, concatMapTo, interval, take } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const result = clicks.pipe( - * concatMapTo(interval(1000).pipe(take(4))), + * concatMapTo(interval(1000).pipe(take(4))) * ); * result.subscribe(x => console.log(x)); * diff --git a/src/internal/operators/concatWith.ts b/src/internal/operators/concatWith.ts index 6fd4b8f36f8..b836b29e228 100644 --- a/src/internal/operators/concatWith.ts +++ b/src/internal/operators/concatWith.ts @@ -13,8 +13,7 @@ import { concat } from './concat'; * Listen for one mouse click, then listen for all mouse moves. * * ```ts - * import { fromEvent } from 'rxjs'; - * import { concatWith, map, take } from 'rxjs/operators'; + * import { fromEvent, map, take, concatWith } from 'rxjs'; * * const clicks$ = fromEvent(document, 'click'); * const moves$ = fromEvent(document, 'mousemove'); diff --git a/src/internal/operators/connect.ts b/src/internal/operators/connect.ts index 0bc14cb9e23..ac1f9ad802c 100644 --- a/src/internal/operators/connect.ts +++ b/src/internal/operators/connect.ts @@ -43,55 +43,54 @@ const DEFAULT_CONFIG: ConnectConfig = { * the `selector` function returns, the observable it returns will be subscribed to, _then_ the * multicast will be connected to the source. * - * ### Example + * ## Example * * Sharing a totally synchronous observable * * ```ts - * import { defer, merge, of } from 'rxjs'; - * import { tap, connect, filter, map } from 'rxjs/operators'; + * import { of, tap, connect, merge, filter, map } from 'rxjs'; * - * const source$ = defer(() => { - * console.log('subscription started'); - * return of(1, 2, 3, 4, 5).pipe( - * tap(n => console.log(`source emitted ${n}`)) - * ); - * }); + * const source$ = of(1, 2, 3, 4, 5).pipe( + * tap({ + * subscribe: () => console.log('subscription started'), + * next: n => console.log(`source emitted ${ n }`) + * }) + * ); * * source$.pipe( * // Notice in here we're merging 3 subscriptions to `shared$`. - * connect((shared$) => merge( - * shared$.pipe(map(n => `all ${n}`)), - * shared$.pipe(filter(n => n % 2 === 0), map(n => `even ${n}`)), - * shared$.pipe(filter(n => n % 2 === 1), map(n => `odd ${n}`)), + * connect(shared$ => merge( + * shared$.pipe(map(n => `all ${ n }`)), + * shared$.pipe(filter(n => n % 2 === 0), map(n => `even ${ n }`)), + * shared$.pipe(filter(n => n % 2 === 1), map(n => `odd ${ n }`)) * )) * ) * .subscribe(console.log); * * // Expected output: (notice only one subscription) - * "subscription started" - * "source emitted 1" - * "all 1" - * "odd 1" - * "source emitted 2" - * "all 2" - * "even 2" - * "source emitted 3" - * "all 3" - * "odd 3" - * "source emitted 4" - * "all 4" - * "even 4" - * "source emitted 5" - * "all 5" - * "odd 5" + * 'subscription started' + * 'source emitted 1' + * 'all 1' + * 'odd 1' + * 'source emitted 2' + * 'all 2' + * 'even 2' + * 'source emitted 3' + * 'all 3' + * 'odd 3' + * 'source emitted 4' + * 'all 4' + * 'even 4' + * 'source emitted 5' + * 'all 5' + * 'odd 5' * ``` * * @param selector A function used to set up the multicast. Gives you a multicast observable * that is not yet connected. With that, you're expected to create and return * and Observable, that when subscribed to, will utilize the multicast observable. * After this function is executed -- and its return value subscribed to -- the - * the operator will subscribe to the source, and the connection will be made. + * operator will subscribe to the source, and the connection will be made. * @param config The configuration object for `connect`. */ export function connect>( diff --git a/src/internal/operators/count.ts b/src/internal/operators/count.ts index 81d037be3f7..8b764f83325 100644 --- a/src/internal/operators/count.ts +++ b/src/internal/operators/count.ts @@ -1,5 +1,6 @@ import { OperatorFunction } from '../types'; import { reduce } from './reduce'; + /** * Counts the number of emissions on the source and emits that number when the * source completes. @@ -21,9 +22,9 @@ import { reduce } from './reduce'; * ## Examples * * Counts how many seconds have passed before the first click happened + * * ```ts - * import { fromEvent, interval } from 'rxjs'; - * import { count, takeUntil } from 'rxjs/operators'; + * import { interval, fromEvent, takeUntil, count } from 'rxjs'; * * const seconds = interval(1000); * const clicks = fromEvent(document, 'click'); @@ -33,9 +34,9 @@ import { reduce } from './reduce'; * ``` * * Counts how many odd numbers are there between 1 and 7 + * * ```ts - * import { range } from 'rxjs'; - * import { count } from 'rxjs/operators'; + * import { range, count } from 'rxjs'; * * const numbers = range(1, 7); * const result = numbers.pipe(count(i => i % 2 === 1)); @@ -55,7 +56,6 @@ import { reduce } from './reduce'; * @return A function that returns an Observable that emits one number that * represents the count of emissions. */ - export function count(predicate?: (value: T, index: number) => boolean): OperatorFunction { return reduce((total, value, i) => (!predicate || predicate(value, i) ? total + 1 : total), 0); } diff --git a/src/internal/operators/debounce.ts b/src/internal/operators/debounce.ts index 1724904c870..05cf58e4d45 100644 --- a/src/internal/operators/debounce.ts +++ b/src/internal/operators/debounce.ts @@ -33,22 +33,23 @@ import { innerFrom } from '../observable/innerFrom'; * same time as they did on the source Observable. * * ## Example + * * Emit the most recent click after a burst of clicks + * * ```ts - * import { fromEvent, interval } from 'rxjs'; - * import { scan, debounce } from 'rxjs/operators'; + * import { fromEvent, scan, debounce, interval } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const result = clicks.pipe( - * scan((i) => ++i, 1), - * debounce((i) => interval(200 * i)) + * scan(i => ++i, 1), + * debounce(i => interval(200 * i)) * ); * result.subscribe(x => console.log(x)); * ``` * * @see {@link audit} * @see {@link auditTime} - * @see {@link debounce} + * @see {@link debounceTime} * @see {@link delay} * @see {@link sample} * @see {@link sampleTime} diff --git a/src/internal/operators/debounceTime.ts b/src/internal/operators/debounceTime.ts index 875116fe881..40f385caade 100644 --- a/src/internal/operators/debounceTime.ts +++ b/src/internal/operators/debounceTime.ts @@ -32,10 +32,11 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * managing timers. * * ## Example + * * Emit the most recent click after a burst of clicks + * * ```ts - * import { fromEvent } from 'rxjs'; - * import { debounceTime } from 'rxjs/operators'; + * import { fromEvent, debounceTime } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const result = clicks.pipe(debounceTime(1000)); @@ -45,7 +46,6 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * @see {@link audit} * @see {@link auditTime} * @see {@link debounce} - * @see {@link debounceTime} * @see {@link sample} * @see {@link sampleTime} * @see {@link throttle} diff --git a/src/internal/operators/defaultIfEmpty.ts b/src/internal/operators/defaultIfEmpty.ts index 53f99b055f5..5853002fdd7 100644 --- a/src/internal/operators/defaultIfEmpty.ts +++ b/src/internal/operators/defaultIfEmpty.ts @@ -16,10 +16,11 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * having emitted any `next` value). * * ## Example - * If no clicks happen in 5 seconds, then emit "no clicks" + * + * If no clicks happen in 5 seconds, then emit 'no clicks' + * * ```ts - * import { fromEvent, interval } from 'rxjs'; - * import { defaultIfEmpty, takeUntil } from 'rxjs/operators'; + * import { fromEvent, takeUntil, interval, defaultIfEmpty } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const clicksBeforeFive = clicks.pipe(takeUntil(interval(5000))); @@ -42,7 +43,7 @@ export function defaultIfEmpty(defaultValue: R): OperatorFunction { + value => { hasValue = true; subscriber.next(value); }, diff --git a/src/internal/operators/delay.ts b/src/internal/operators/delay.ts index 5758c95016e..299259b0e92 100644 --- a/src/internal/operators/delay.ts +++ b/src/internal/operators/delay.ts @@ -20,10 +20,11 @@ import { timer } from '../observable/timer'; * Observable execution until the given date occurs. * * ## Examples + * * Delay each click by one second + * * ```ts - * import { fromEvent } from 'rxjs'; - * import { delay } from 'rxjs/operators'; + * import { fromEvent, delay } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const delayedClicks = clicks.pipe(delay(1000)); // each click emitted after 1 second @@ -31,9 +32,9 @@ import { timer } from '../observable/timer'; * ``` * * Delay all clicks until a future date happens + * * ```ts - * import { fromEvent } from 'rxjs'; - * import { delay } from 'rxjs/operators'; + * import { fromEvent, delay } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const date = new Date('March 15, 2050 12:00:00'); // in the future diff --git a/src/internal/operators/delayWhen.ts b/src/internal/operators/delayWhen.ts index 208438fffb4..2362dc35081 100644 --- a/src/internal/operators/delayWhen.ts +++ b/src/internal/operators/delayWhen.ts @@ -39,14 +39,15 @@ export function delayWhen(delayDurationSelector: (value: T, index: number) => * Observable is subscribed. * * ## Example + * * Delay each click by a random amount of time, between 0 and 5 seconds + * * ```ts - * import { fromEvent, interval } from 'rxjs'; - * import { delayWhen } from 'rxjs/operators'; + * import { fromEvent, delayWhen, interval } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const delayedClicks = clicks.pipe( - * delayWhen(event => interval(Math.random() * 5000)), + * delayWhen(() => interval(Math.random() * 5000)), * ); * delayedClicks.subscribe(x => console.log(x)); * ``` diff --git a/src/internal/operators/dematerialize.ts b/src/internal/operators/dematerialize.ts index 2c6e8e3d8b3..6aaafffa357 100644 --- a/src/internal/operators/dematerialize.ts +++ b/src/internal/operators/dematerialize.ts @@ -25,19 +25,18 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * Convert an Observable of Notifications to an actual Observable * * ```ts - * import { of } from 'rxjs'; - * import { dematerialize } from 'rxjs/operators'; + * import { NextNotification, ErrorNotification, of, dematerialize } from 'rxjs'; * - * const notifA = { kind: 'N', value: 'A' }; - * const notifB = { kind: 'N', value: 'B' }; - * const notifE = { kind: 'E', error: new TypeError('x.toUpperCase is not a function') } + * const notifA = >{ kind: 'N', value: 'A' }; + * const notifB = >{ kind: 'N', value: 'B' }; + * const notifE = { kind: 'E', error: new TypeError('x.toUpperCase is not a function') }; * * const materialized = of(notifA, notifB, notifE); * * const upperCase = materialized.pipe(dematerialize()); * upperCase.subscribe({ - * next: x => console.log(x), - * error: e => console.error(e) + * next: x => console.log(x), + * error: e => console.error(e) * }); * * // Results in: @@ -45,6 +44,7 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * // B * // TypeError: x.toUpperCase is not a function * ``` + * * @see {@link materialize} * * @return A function that returns an Observable that emits items and @@ -53,6 +53,6 @@ import { OperatorSubscriber } from './OperatorSubscriber'; */ export function dematerialize>(): OperatorFunction> { return operate((source, subscriber) => { - source.subscribe(new OperatorSubscriber(subscriber, (notification) => observeNotification(notification, subscriber))); + source.subscribe(new OperatorSubscriber(subscriber, notification => observeNotification(notification, subscriber))); }); } diff --git a/src/internal/operators/distinct.ts b/src/internal/operators/distinct.ts index b713204fdc5..4e9701142f5 100644 --- a/src/internal/operators/distinct.ts +++ b/src/internal/operators/distinct.ts @@ -7,8 +7,8 @@ import { noop } from '../util/noop'; /** * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items. * - * If a keySelector function is provided, then it will project each value from the source observable into a new value that it will - * check for equality with previously projected values. If a keySelector function is not provided, it will use each value from the + * If a `keySelector` function is provided, then it will project each value from the source observable into a new value that it will + * check for equality with previously projected values. If the `keySelector` function is not provided, it will use each value from the * source observable directly with an equality check against previous values. * * In JavaScript runtimes that support `Set`, this operator will use a `Set` to improve performance of the distinct value checking. @@ -23,13 +23,10 @@ import { noop } from '../util/noop'; * A simple example with numbers * * ```ts - * import { of } from 'rxjs'; - * import { distinct } from 'rxjs/operators'; + * import { of, distinct } from 'rxjs'; * * of(1, 1, 2, 2, 2, 1, 2, 3, 4, 3, 2, 1) - * .pipe( - * distinct() - * ) + * .pipe(distinct()) * .subscribe(x => console.log(x)); * * // Outputs @@ -39,25 +36,18 @@ import { noop } from '../util/noop'; * // 4 * ``` * - * An example using a keySelector function + * An example using the `keySelector` function * * ```ts - * import { of } from 'rxjs'; - * import { distinct } from 'rxjs/operators'; - * - * interface Person { - * age: number, - * name: string - * } + * import { of, distinct } from 'rxjs'; * * of( - * { age: 4, name: 'Foo'}, - * { age: 7, name: 'Bar'}, - * { age: 5, name: 'Foo'} - * ).pipe( - * distinct((p: Person) => p.name) - * ) - * .subscribe(x => console.log(x)); + * { age: 4, name: 'Foo'}, + * { age: 7, name: 'Bar'}, + * { age: 5, name: 'Foo'} + * ) + * .pipe(distinct(({name}) => name)) + * .subscribe(x => console.log(x)); * * // Outputs * // { age: 4, name: 'Foo' } @@ -75,7 +65,7 @@ export function distinct(keySelector?: (value: T) => K, flushes?: Observab return operate((source, subscriber) => { const distinctKeys = new Set(); source.subscribe( - new OperatorSubscriber(subscriber, (value) => { + new OperatorSubscriber(subscriber, value => { const key = keySelector ? keySelector(value) : value; if (!distinctKeys.has(key)) { distinctKeys.add(key); diff --git a/src/internal/operators/distinctUntilChanged.ts b/src/internal/operators/distinctUntilChanged.ts index 30f87bcc961..f4fb73db9e6 100644 --- a/src/internal/operators/distinctUntilChanged.ts +++ b/src/internal/operators/distinctUntilChanged.ts @@ -13,32 +13,27 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * 3. If the value pushed by the source is determined to be unequal by this check, that value is emitted and * becomes the new "previously emitted value" internally. * - * ## Example + * ## Examples * * A very basic example with no `comparator`. Note that `1` is emitted more than once, * because it's distinct in comparison to the _previously emitted_ value, * not in comparison to _all other emitted values_. * * ```ts - * import { of } from 'rxjs'; - * import { distinctUntilChanged } from 'rxjs/operators'; + * import { of, distinctUntilChanged } from 'rxjs'; * - * of(1, 1, 1, 2, 2, 2, 1, 1, 3, 3).pipe( - * distinctUntilChanged() - * ) - * .subscribe(console.log); + * of(1, 1, 1, 2, 2, 2, 1, 1, 3, 3) + * .pipe(distinctUntilChanged()) + * .subscribe(console.log); * // Logs: 1, 2, 1, 3 * ``` * - * ## Example - * * With a `comparator`, you can do custom comparisons. Let's say * you only want to emit a value when all of its components have * changed: * * ```ts - * import { of } from 'rxjs'; - * import { distinctUntilChanged } from 'rxjs/operators'; + * import { of, distinctUntilChanged } from 'rxjs'; * * const totallyDifferentBuilds$ = of( * { engineVersion: '1.1.0', transmissionVersion: '1.2.0' }, @@ -58,20 +53,17 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * totallyDifferentBuilds$.subscribe(console.log); * * // Logs: - * // {engineVersion: "1.1.0", transmissionVersion: "1.2.0"} - * // {engineVersion: "1.3.0", transmissionVersion: "1.4.0"} - * // {engineVersion: "2.0.0", transmissionVersion: "1.5.0"} + * // { engineVersion: '1.1.0', transmissionVersion: '1.2.0' } + * // { engineVersion: '1.3.0', transmissionVersion: '1.4.0' } + * // { engineVersion: '2.0.0', transmissionVersion: '1.5.0' } * ``` * - * ## Example - * * You can also provide a custom `comparator` to check that emitted * changes are only in one direction. Let's say you only want to get * the next record temperature: * * ```ts - * import { of } from "rxjs"; - * import { distinctUntilChanged } from "rxjs/operators"; + * import { of, distinctUntilChanged } from 'rxjs'; * * const temps$ = of(30, 31, 20, 34, 33, 29, 35, 20); * @@ -114,11 +106,11 @@ export function distinctUntilChanged(comparator?: (previous: T, current: T) = * ```ts * // A stream of updates to a given account * const accountUpdates$ = of( - * { updatedBy: "blesh", data: [] }, - * { updatedBy: "blesh", data: [] }, - * { updatedBy: "ncjamieson", data: [] }, - * { updatedBy: "ncjamieson", data: [] }, - * { updatedBy: "blesh", data: [] } + * { updatedBy: 'blesh', data: [] }, + * { updatedBy: 'blesh', data: [] }, + * { updatedBy: 'ncjamieson', data: [] }, + * { updatedBy: 'ncjamieson', data: [] }, + * { updatedBy: 'blesh', data: [] } * ); * * // We only want the events where it changed hands @@ -128,9 +120,9 @@ export function distinctUntilChanged(comparator?: (previous: T, current: T) = * * changedHands$.subscribe(console.log); * // Logs: - * // {updatedBy: "blesh", data: Array[0]} - * // {updatedBy: "ncjamieson", data: Array[0]} - * // {updatedBy: "blesh", data: Array[0]} + * // { updatedBy: 'blesh', data: Array[0] } + * // { updatedBy: 'ncjamieson', data: Array[0] } + * // { updatedBy: 'blesh', data: Array[0] } * ``` * * @param comparator A function used to compare the previous and current keys for @@ -161,7 +153,7 @@ export function distinctUntilChanged( let first = true; source.subscribe( - new OperatorSubscriber(subscriber, (value) => { + new OperatorSubscriber(subscriber, value => { // We always call the key selector. const currentKey = keySelector(value); diff --git a/src/internal/operators/distinctUntilKeyChanged.ts b/src/internal/operators/distinctUntilKeyChanged.ts index 45112b9219f..3ab6c2d1d4f 100644 --- a/src/internal/operators/distinctUntilKeyChanged.ts +++ b/src/internal/operators/distinctUntilKeyChanged.ts @@ -15,25 +15,21 @@ export function distinctUntilKeyChanged(key: K, compare: ( * If a comparator function is not provided, an equality check is used by default. * * ## Examples + * * An example comparing the name of persons - * ```typescript - * import { of } from 'rxjs'; - * import { distinctUntilKeyChanged } from 'rxjs/operators'; * - * interface Person { - * age: number, - * name: string - * } + * ```ts + * import { of, distinctUntilKeyChanged } from 'rxjs'; * - *of( - * { age: 4, name: 'Foo'}, - * { age: 7, name: 'Bar'}, - * { age: 5, name: 'Foo'}, - * { age: 6, name: 'Foo'}, - * ).pipe( - * distinctUntilKeyChanged('name'), - * ) - * .subscribe(x => console.log(x)); + * of( + * { age: 4, name: 'Foo' }, + * { age: 7, name: 'Bar' }, + * { age: 5, name: 'Foo' }, + * { age: 6, name: 'Foo' } + * ).pipe( + * distinctUntilKeyChanged('name') + * ) + * .subscribe(x => console.log(x)); * * // displays: * // { age: 4, name: 'Foo' } @@ -42,24 +38,19 @@ export function distinctUntilKeyChanged(key: K, compare: ( * ``` * * An example comparing the first letters of the name - * ```typescript - * import { of } from 'rxjs'; - * import { distinctUntilKeyChanged } from 'rxjs/operators'; * - * interface Person { - * age: number, - * name: string - * } + * ```ts + * import { of, distinctUntilKeyChanged } from 'rxjs'; * - *of( - * { age: 4, name: 'Foo1'}, - * { age: 7, name: 'Bar'}, - * { age: 5, name: 'Foo2'}, - * { age: 6, name: 'Foo3'}, - * ).pipe( - * distinctUntilKeyChanged('name', (x: string, y: string) => x.substring(0, 3) === y.substring(0, 3)), - * ) - * .subscribe(x => console.log(x)); + * of( + * { age: 4, name: 'Foo1' }, + * { age: 7, name: 'Bar' }, + * { age: 5, name: 'Foo2' }, + * { age: 6, name: 'Foo3' } + * ).pipe( + * distinctUntilKeyChanged('name', (x, y) => x.substring(0, 3) === y.substring(0, 3)) + * ) + * .subscribe(x => console.log(x)); * * // displays: * // { age: 4, name: 'Foo1' } @@ -75,6 +66,9 @@ export function distinctUntilKeyChanged(key: K, compare: ( * @return A function that returns an Observable that emits items from the * source Observable with distinct values based on the key specified. */ -export function distinctUntilKeyChanged(key: K, compare?: (x: T[K], y: T[K]) => boolean): MonoTypeOperatorFunction { - return distinctUntilChanged((x: T, y: T) => compare ? compare(x[key], y[key]) : x[key] === y[key]); +export function distinctUntilKeyChanged( + key: K, + compare?: (x: T[K], y: T[K]) => boolean +): MonoTypeOperatorFunction { + return distinctUntilChanged((x: T, y: T) => (compare ? compare(x[key], y[key]) : x[key] === y[key])); } diff --git a/src/internal/operators/elementAt.ts b/src/internal/operators/elementAt.ts index 21454089e01..6a817fc5dd8 100644 --- a/src/internal/operators/elementAt.ts +++ b/src/internal/operators/elementAt.ts @@ -21,10 +21,11 @@ import { take } from './take'; * `ArgumentOutOfRangeError` error. * * ## Example + * * Emit only the third click event + * * ```ts - * import { fromEvent } from 'rxjs'; - * import { elementAt } from 'rxjs/operators'; + * import { fromEvent, elementAt } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const result = clicks.pipe(elementAt(2)); diff --git a/src/internal/operators/endWith.ts b/src/internal/operators/endWith.ts index ed5e0985c19..a5e9d6cd223 100644 --- a/src/internal/operators/endWith.ts +++ b/src/internal/operators/endWith.ts @@ -31,8 +31,7 @@ export function endWith(...values: A): OperatorFun * stop when a user clicks anywhere on the document. * * ```ts - * import { interval, fromEvent } from 'rxjs'; - * import { map, startWith, takeUntil, endWith } from 'rxjs/operators'; + * import { interval, map, fromEvent, startWith, takeUntil, endWith } from 'rxjs'; * * const ticker$ = interval(5000).pipe( * map(() => 'tick'), @@ -48,21 +47,21 @@ export function endWith(...values: A): OperatorFun * .subscribe(x => console.log(x)); * * // Result (assuming a user clicks after 15 seconds) - * // "interval started" - * // "tick" - * // "tick" - * // "tick" - * // "interval ended by click" + * // 'interval started' + * // 'tick' + * // 'tick' + * // 'tick' + * // 'interval ended by click' * ``` * + * @see {@link startWith} + * @see {@link concat} + * @see {@link takeUntil} + * * @param values Items you want the modified Observable to emit last. * @return A function that returns an Observable that emits all values from the * source, then synchronously emits the provided value(s) immediately after the * source completes. - * - * @see {@link startWith} - * @see {@link concat} - * @see {@link takeUntil} */ export function endWith(...values: Array): MonoTypeOperatorFunction { return (source: Observable) => concat(source, of(...values)) as Observable; diff --git a/src/internal/operators/every.ts b/src/internal/operators/every.ts index c7c52d4bcbb..186d3a4ee3f 100644 --- a/src/internal/operators/every.ts +++ b/src/internal/operators/every.ts @@ -25,15 +25,15 @@ export function every(predicate: (value: T, index: number, source: Observable * ![](every.png) * * ## Example + * * A simple example emitting true if all elements are less than 5, false otherwise + * * ```ts - * import { of } from 'rxjs'; - * import { every } from 'rxjs/operators'; + * import { of, every } from 'rxjs'; * - * of(1, 2, 3, 4, 5, 6).pipe( - * every(x => x < 5), - * ) - * .subscribe(x => console.log(x)); // -> false + * of(1, 2, 3, 4, 5, 6) + * .pipe(every(x => x < 5)) + * .subscribe(x => console.log(x)); // -> false * ``` * * @param {function} predicate A function for determining if an item meets a specified condition. @@ -50,7 +50,7 @@ export function every( source.subscribe( new OperatorSubscriber( subscriber, - (value) => { + value => { if (!predicate.call(thisArg, value, index++, source)) { subscriber.next(false); subscriber.complete(); diff --git a/src/internal/operators/exhaustAll.ts b/src/internal/operators/exhaustAll.ts index d5ebd59fa48..7e87dcb7d7b 100644 --- a/src/internal/operators/exhaustAll.ts +++ b/src/internal/operators/exhaustAll.ts @@ -13,23 +13,24 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * * ![](exhaust.png) * - * `exhaust` subscribes to an Observable that emits Observables, also known as a + * `exhaustAll` subscribes to an Observable that emits Observables, also known as a * higher-order Observable. Each time it observes one of these emitted inner * Observables, the output Observable begins emitting the items emitted by that * inner Observable. So far, it behaves like {@link mergeAll}. However, - * `exhaust` ignores every new inner Observable if the previous Observable has + * `exhaustAll` ignores every new inner Observable if the previous Observable has * not yet completed. Once that one completes, it will accept and flatten the * next inner Observable and repeat this process. * * ## Example + * * Run a finite timer for each click, only if there is no currently active timer + * * ```ts - * import { fromEvent, interval } from 'rxjs'; - * import { exhaustAll, map, take } from 'rxjs/operators'; + * import { fromEvent, map, interval, take, exhaustAll } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const higherOrder = clicks.pipe( - * map((ev) => interval(1000).pipe(take(5))), + * map(() => interval(1000).pipe(take(5))) * ); * const result = higherOrder.pipe(exhaustAll()); * result.subscribe(x => console.log(x)); @@ -54,7 +55,7 @@ export function exhaustAll>(): OperatorFunction { + inner => { if (!innerSub) { innerSub = innerFrom(inner).subscribe( new OperatorSubscriber(subscriber, undefined, () => { diff --git a/src/internal/operators/exhaustMap.ts b/src/internal/operators/exhaustMap.ts index b2ea51b6f4b..c14af15b517 100644 --- a/src/internal/operators/exhaustMap.ts +++ b/src/internal/operators/exhaustMap.ts @@ -41,14 +41,15 @@ export function exhaustMap( * and repeat this process. * * ## Example + * * Run a finite timer for each click, only if there is no currently active timer + * * ```ts - * import { fromEvent, interval } from 'rxjs'; - * import { exhaustMap, take } from 'rxjs/operators'; + * import { fromEvent, exhaustMap, interval, take } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const result = clicks.pipe( - * exhaustMap(ev => interval(1000).pipe(take(5))) + * exhaustMap(() => interval(1000).pipe(take(5))) * ); * result.subscribe(x => console.log(x)); * ``` @@ -81,7 +82,7 @@ export function exhaustMap>( source.subscribe( new OperatorSubscriber( subscriber, - (outerValue) => { + outerValue => { if (!innerSub) { innerSub = new OperatorSubscriber(subscriber, undefined, () => { innerSub = null; diff --git a/src/internal/operators/expand.ts b/src/internal/operators/expand.ts index b79f6376e24..84b7e347a66 100644 --- a/src/internal/operators/expand.ts +++ b/src/internal/operators/expand.ts @@ -41,16 +41,17 @@ export function expand>( * *expand* behaves recursively. * * ## Example + * * Start emitting the powers of two on every click, at most 10 of them + * * ```ts - * import { fromEvent, of } from 'rxjs'; - * import { expand, mapTo, delay, take } from 'rxjs/operators'; + * import { fromEvent, map, expand, of, delay, take } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const powersOfTwo = clicks.pipe( - * mapTo(1), + * map(() => 1), * expand(x => of(2 * x).pipe(delay(1000))), - * take(10), + * take(10) * ); * powersOfTwo.subscribe(x => console.log(x)); * ``` diff --git a/src/internal/operators/filter.ts b/src/internal/operators/filter.ts index 97d5e8b62dc..cd6d8f2fffa 100644 --- a/src/internal/operators/filter.ts +++ b/src/internal/operators/filter.ts @@ -25,17 +25,18 @@ export function filter(predicate: (value: T, index: number) => boolean): Mono * function and only emits those values that yielded `true`. * * ## Example + * * Emit only click events whose target was a DIV element + * * ```ts - * import { fromEvent } from 'rxjs'; - * import { filter } from 'rxjs/operators'; + * import { fromEvent, filter } from 'rxjs'; * * const div = document.createElement('div'); * div.style.cssText = `width: 200px;height: 200px;background: #09c;`; * document.body.appendChild(div); * * const clicks = fromEvent(document, 'click'); - * const clicksOnDivs = clicks.pipe(filter(ev => ev.target.tagName === 'DIV')); + * const clicksOnDivs = clicks.pipe(filter(ev => (ev.target).tagName === 'DIV')); * clicksOnDivs.subscribe(x => console.log(x)); * ``` * @@ -68,7 +69,7 @@ export function filter(predicate: (value: T, index: number) => boolean, thisA // Call the predicate with the appropriate `this` context, // if the predicate returns `true`, then send the value // to the consumer. - new OperatorSubscriber(subscriber, (value) => predicate.call(thisArg, value, index++) && subscriber.next(value)) + new OperatorSubscriber(subscriber, value => predicate.call(thisArg, value, index++) && subscriber.next(value)) ); }); } diff --git a/src/internal/operators/finalize.ts b/src/internal/operators/finalize.ts index aa4575be356..7ab08b239c8 100644 --- a/src/internal/operators/finalize.ts +++ b/src/internal/operators/finalize.ts @@ -7,34 +7,33 @@ import { operate } from '../util/lift'; * The specified function will also be called when the subscriber explicitly unsubscribes. * * ## Examples + * * Execute callback function when the observable completes * * ```ts - * import { interval } from 'rxjs'; - * import { take, finalize } from 'rxjs/operators'; + * import { interval, take, finalize } from 'rxjs'; * * // emit value in sequence every 1 second * const source = interval(1000); * const example = source.pipe( * take(5), //take only the first 5 values * finalize(() => console.log('Sequence complete')) // Execute when the observable completes - * ) + * ); * const subscribe = example.subscribe(val => console.log(val)); * * // results: - * // 0 - * // 1 - * // 2 - * // 3 - * // 4 - * // 'Sequence complete' + * // 0 + * // 1 + * // 2 + * // 3 + * // 4 + * // 'Sequence complete' * ``` * * Execute callback function when the subscriber explicitly unsubscribes * * ```ts - * import { interval, timer, noop } from 'rxjs'; - * import { finalize, tap } from 'rxjs/operators'; + * import { interval, finalize, tap, noop, timer } from 'rxjs'; * * const source = interval(100).pipe( * finalize(() => console.log('[finalize] Called')), @@ -54,9 +53,9 @@ import { operate } from '../util/lift'; * timer(150).subscribe(() => sub.unsubscribe()); * * // results: - * // '[next] Called' - * // 0 - * // '[finalize] Called' + * // '[next] Called' + * // 0 + * // '[finalize] Called' * ``` * * @param {function} callback Function to be called when source terminates. diff --git a/src/internal/operators/find.ts b/src/internal/operators/find.ts index 89952ce621f..ca163fc3721 100644 --- a/src/internal/operators/find.ts +++ b/src/internal/operators/find.ts @@ -35,17 +35,18 @@ export function find(predicate: (value: T, index: number, source: Observable< * (emits `undefined` instead). * * ## Example + * * Find and emit the first click that happens on a DIV element + * * ```ts - * import { fromEvent } from 'rxjs'; - * import { find } from 'rxjs/operators'; + * import { fromEvent, find } from 'rxjs'; * * const div = document.createElement('div'); * div.style.cssText = 'width: 200px; height: 200px; background: #09c;'; * document.body.appendChild(div); * * const clicks = fromEvent(document, 'click'); - * const result = clicks.pipe(find(ev => ev.target.tagName === 'DIV')); + * const result = clicks.pipe(find(ev => (ev.target).tagName === 'DIV')); * result.subscribe(x => console.log(x)); * ``` * @@ -79,7 +80,7 @@ export function createFind( source.subscribe( new OperatorSubscriber( subscriber, - (value) => { + value => { const i = index++; if (predicate.call(thisArg, value, i, source)) { subscriber.next(findIndex ? i : value); diff --git a/src/internal/operators/findIndex.ts b/src/internal/operators/findIndex.ts index 6016493f905..7a9d943cbcc 100644 --- a/src/internal/operators/findIndex.ts +++ b/src/internal/operators/findIndex.ts @@ -29,17 +29,18 @@ export function findIndex(predicate: (value: T, index: number, source: Observ * an error if a valid value is not found. * * ## Example + * * Emit the index of first click that happens on a DIV element + * * ```ts - * import { fromEvent } from 'rxjs'; - * import { findIndex } from 'rxjs/operators'; + * import { fromEvent, findIndex } from 'rxjs'; * * const div = document.createElement('div'); * div.style.cssText = 'width: 200px; height: 200px; background: #09c;'; * document.body.appendChild(div); * * const clicks = fromEvent(document, 'click'); - * const result = clicks.pipe(findIndex(ev => ev.target.tagName === 'DIV')); + * const result = clicks.pipe(findIndex(ev => (ev.target).tagName === 'DIV')); * result.subscribe(x => console.log(x)); * ``` * diff --git a/src/internal/operators/first.ts b/src/internal/operators/first.ts index 4339bd8c346..b3ca1f8e466 100644 --- a/src/internal/operators/first.ts +++ b/src/internal/operators/first.ts @@ -38,10 +38,11 @@ export function first( * `defaultValue` was not provided and a matching element is not found. * * ## Examples + * * Emit only the first click that happens on the DOM + * * ```ts - * import { fromEvent } from 'rxjs'; - * import { first } from 'rxjs/operators'; + * import { fromEvent, first } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const result = clicks.pipe(first()); @@ -49,16 +50,16 @@ export function first( * ``` * * Emits the first click that happens on a DIV + * * ```ts - * import { fromEvent } from 'rxjs'; - * import { first } from 'rxjs/operators'; + * import { fromEvent, first } from 'rxjs'; * * const div = document.createElement('div'); * div.style.cssText = 'width: 200px; height: 200px; background: #09c;'; * document.body.appendChild(div); * * const clicks = fromEvent(document, 'click'); - * const result = clicks.pipe(first(ev => ev.target.tagName === 'DIV')); + * const result = clicks.pipe(first(ev => (ev.target).tagName === 'DIV')); * result.subscribe(x => console.log(x)); * ``` * @@ -72,7 +73,7 @@ export function first( * * @param {function(value: T, index: number, source: Observable): boolean} [predicate] * An optional function called with each item to test for condition matching. - * @param {R} [defaultValue] The default value emitted in case no valid value + * @param {D} [defaultValue] The default value emitted in case no valid value * was found on the source. * @return A function that returns an Observable that emits the first item that * matches the condition. diff --git a/src/internal/operators/groupBy.ts b/src/internal/operators/groupBy.ts index c79df357b62..0cb52632945 100644 --- a/src/internal/operators/groupBy.ts +++ b/src/internal/operators/groupBy.ts @@ -68,39 +68,33 @@ export function groupBy( * * ## Examples * - * ### Group objects by id and return as array + * Group objects by `id` and return as array * * ```ts - * import { of } from 'rxjs'; - * import { mergeMap, groupBy, reduce } from 'rxjs/operators'; + * import { of, groupBy, mergeMap, reduce } from 'rxjs'; * * of( - * {id: 1, name: 'JavaScript'}, - * {id: 2, name: 'Parcel'}, - * {id: 2, name: 'webpack'}, - * {id: 1, name: 'TypeScript'}, - * {id: 3, name: 'TSLint'} + * { id: 1, name: 'JavaScript' }, + * { id: 2, name: 'Parcel' }, + * { id: 2, name: 'webpack' }, + * { id: 1, name: 'TypeScript' }, + * { id: 3, name: 'TSLint' } * ).pipe( * groupBy(p => p.id), - * mergeMap((group$) => group$.pipe(reduce((acc, cur) => [...acc, cur], []))) + * mergeMap(group$ => group$.pipe(reduce((acc, cur) => [...acc, cur], []))) * ) * .subscribe(p => console.log(p)); * * // displays: - * // [ { id: 1, name: 'JavaScript'}, - * // { id: 1, name: 'TypeScript'} ] - * // - * // [ { id: 2, name: 'Parcel'}, - * // { id: 2, name: 'webpack'} ] - * // + * // [ { id: 1, name: 'JavaScript'}, { id: 1, name: 'TypeScript'} ] + * // [ { id: 2, name: 'Parcel'}, { id: 2, name: 'webpack'} ] * // [ { id: 3, name: 'TSLint'} ] * ``` * - * ### Pivot data on the id field + * Pivot data on the `id` field * * ```ts - * import { of } from 'rxjs'; - * import { groupBy, map, mergeMap, reduce } from 'rxjs/operators'; + * import { of, groupBy, mergeMap, reduce, map } from 'rxjs'; * * of( * { id: 1, name: 'JavaScript' }, @@ -108,15 +102,12 @@ export function groupBy( * { id: 2, name: 'webpack' }, * { id: 1, name: 'TypeScript' }, * { id: 3, name: 'TSLint' } + * ).pipe( + * groupBy(p => p.id, { element: p => p.name }), + * mergeMap(group$ => group$.pipe(reduce((acc, cur) => [...acc, cur], [`${ group$.key }`]))), + * map(arr => ({ id: parseInt(arr[0], 10), values: arr.slice(1) })) * ) - * .pipe( - * groupBy(p => p.id, { element: p => p.name }), - * mergeMap(group$ => - * group$.pipe(reduce((acc, cur) => [...acc, cur], [`${group$.key}`])) - * ), - * map(arr => ({ id: parseInt(arr[0], 10), values: arr.slice(1) })) - * ) - * .subscribe(p => console.log(p)); + * .subscribe(p => console.log(p)); * * // displays: * // { id: 1, values: [ 'JavaScript', 'TypeScript' ] } @@ -172,7 +163,7 @@ export function groupBy( // Used to handle errors from the source, AND errors that occur during the // next call from the source. - const handleError = (err: any) => notify((consumer) => consumer.error(err)); + const handleError = (err: any) => notify(consumer => consumer.error(err)); // Capturing a reference to this, because we need a handle to it // in `createGroupedObservable` below. This is what we use to @@ -236,7 +227,7 @@ export function groupBy( } }, // Source completes. - () => notify((consumer) => consumer.complete()), + () => notify(consumer => consumer.complete()), // Error from the source. handleError, // Free up memory. @@ -255,7 +246,7 @@ export function groupBy( * @param groupSubject The subject that fuels the group */ function createGroupedObservable(key: K, groupSubject: SubjectLike) { - const result: any = new Observable((groupSubscriber) => { + const result: any = new Observable(groupSubscriber => { groupBySourceSubscriber.activeGroups++; const innerSub = groupSubject.subscribe(groupSubscriber); return () => { diff --git a/src/internal/operators/ignoreElements.ts b/src/internal/operators/ignoreElements.ts index 8df5dd0ec62..4b85c9c27d7 100644 --- a/src/internal/operators/ignoreElements.ts +++ b/src/internal/operators/ignoreElements.ts @@ -8,29 +8,32 @@ import { noop } from '../util/noop'; * * ![](ignoreElements.png) * - * The _IgnoreElements_ operator suppresses all of the items emitted by the source Observable, + * The `ignoreElements` operator suppresses all items emitted by the source Observable, * but allows its termination notification (either `error` or `complete`) to pass through unchanged. * * If you do not care about the items being emitted by an Observable, but you do want to be notified * when it completes or when it terminates with an error, you can apply the `ignoreElements` operator * to the Observable, which will ensure that it will never call its observers’ `next` handlers. * - * ## Examples + * ## Example + * + * Ignore all `next` emissions from the source + * * ```ts - * import { of } from 'rxjs'; - * import { ignoreElements } from 'rxjs/operators'; - * - * of('you', 'talking', 'to', 'me').pipe( - * ignoreElements(), - * ) - * .subscribe({ - * next: word => console.log(word), - * error: err => console.log('error:', err), - * complete: () => console.log('the end'), - * }); + * import { of, ignoreElements } from 'rxjs'; + * + * of('you', 'talking', 'to', 'me') + * .pipe(ignoreElements()) + * .subscribe({ + * next: word => console.log(word), + * error: err => console.log('error:', err), + * complete: () => console.log('the end'), + * }); + * * // result: * // 'the end' * ``` + * * @return A function that returns an empty Observable that only calls * `complete` or `error`, based on which one is called by the source * Observable. diff --git a/src/internal/operators/isEmpty.ts b/src/internal/operators/isEmpty.ts index 4c7996b9067..5947b2b702c 100644 --- a/src/internal/operators/isEmpty.ts +++ b/src/internal/operators/isEmpty.ts @@ -22,11 +22,10 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * * ## Examples * - * Emit `false` for a non-empty Observable. + * Emit `false` for a non-empty Observable * * ```ts - * import { Subject } from 'rxjs'; - * import { isEmpty } from 'rxjs/operators'; + * import { Subject, isEmpty } from 'rxjs'; * * const source = new Subject(); * const result = source.pipe(isEmpty()); @@ -46,11 +45,10 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * // c * ``` * - * Emit `true` for an empty Observable. + * Emit `true` for an empty Observable * * ```ts - * import { EMPTY } from 'rxjs'; - * import { isEmpty } from 'rxjs/operators'; + * import { EMPTY, isEmpty } from 'rxjs'; * * const result = EMPTY.pipe(isEmpty()); * result.subscribe(x => console.log(x)); @@ -60,7 +58,7 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * ``` * * @see {@link count} - * @see {@link index/EMPTY} + * @see {@link EMPTY} * * @return A function that returns an Observable that emits boolean value * indicating whether the source Observable was empty or not. diff --git a/src/internal/operators/last.ts b/src/internal/operators/last.ts index 5117db061ae..a046922f87d 100644 --- a/src/internal/operators/last.ts +++ b/src/internal/operators/last.ts @@ -31,27 +31,34 @@ export function last( * returns the last value or if a predicate is provided last value that matches the predicate. It returns the * given default value if no notification is emitted or matches the predicate. * - * ## Example - * Last alphabet from the sequence. + * ## Examples + * + * Last alphabet from the sequence + * * ```ts - * import { from } from 'rxjs'; - * import { last } from 'rxjs/operators'; + * import { from, last } from 'rxjs'; * * const source = from(['x', 'y', 'z']); - * const example = source.pipe(last()); - * //output: "Last alphabet: z" - * example.subscribe(val => console.log(`Last alphabet: ${val}`)); + * const result = source.pipe(last()); + * + * result.subscribe(value => console.log(`Last alphabet: ${ value }`)); + * + * // Outputs + * // Last alphabet: z * ``` * - * Default value when the value in the predicate is not matched. + * Default value when the value in the predicate is not matched + * * ```ts - * import { from } from 'rxjs'; - * import { last } from 'rxjs/operators'; + * import { from, last } from 'rxjs'; * * const source = from(['x', 'y', 'z']); - * const example = source.pipe(last(char => char === 'a','not exist')); - * //output: "'a' is not exist." - * example.subscribe(val => console.log(`'a' is ${val}.`)); + * const result = source.pipe(last(char => char === 'a', 'not found')); + * + * result.subscribe(value => console.log(`'a' is ${ value }.`)); + * + * // Outputs + * // 'a' is not found. * ``` * * @see {@link skip} diff --git a/src/internal/operators/map.ts b/src/internal/operators/map.ts index 3e4e5135584..59a3377371e 100644 --- a/src/internal/operators/map.ts +++ b/src/internal/operators/map.ts @@ -21,13 +21,15 @@ export function map(project: (this: A, value: T, index: number) => R, t * Observable. * * ## Example - * Map every click to the clientX position of that click + * + * Map every click to the `clientX` position of that click + * * ```ts - * import { fromEvent } from 'rxjs'; - * import { map } from 'rxjs/operators'; + * import { fromEvent, map } from 'rxjs'; * - * const clicks = fromEvent(document, 'click'); + * const clicks = fromEvent(document, 'click'); * const positions = clicks.pipe(map(ev => ev.clientX)); + * * positions.subscribe(x => console.log(x)); * ``` * diff --git a/src/internal/operators/mapTo.ts b/src/internal/operators/mapTo.ts index 4608b00d055..0f8c72a1ec3 100644 --- a/src/internal/operators/mapTo.ts +++ b/src/internal/operators/mapTo.ts @@ -19,13 +19,15 @@ export function mapTo(value: R): OperatorFunction; * and simply uses the emission moment to know when to emit the given `value`. * * ## Example - * Map every click to the string 'Hi' + * + * Map every click to the string `'Hi'` + * * ```ts - * import { fromEvent } from 'rxjs'; - * import { mapTo } from 'rxjs/operators'; + * import { fromEvent, mapTo } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const greetings = clicks.pipe(mapTo('Hi')); + * * greetings.subscribe(x => console.log(x)); * ``` * diff --git a/src/internal/operators/materialize.ts b/src/internal/operators/materialize.ts index 70257b9bfef..56089e67286 100644 --- a/src/internal/operators/materialize.ts +++ b/src/internal/operators/materialize.ts @@ -30,20 +30,18 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * Convert a faulty Observable to an Observable of Notifications * * ```ts - * import { of } from 'rxjs'; - * import { materialize, map } from 'rxjs/operators'; + * import { of, materialize, map } from 'rxjs'; * * const letters = of('a', 'b', 13, 'd'); - * const upperCase = letters.pipe(map(x => x.toUpperCase())); + * const upperCase = letters.pipe(map((x: any) => x.toUpperCase())); * const materialized = upperCase.pipe(materialize()); + * * materialized.subscribe(x => console.log(x)); * * // Results in the following: - * // - Notification {kind: "N", value: "A", error: undefined, hasValue: true} - * // - Notification {kind: "N", value: "B", error: undefined, hasValue: true} - * // - Notification {kind: "E", value: undefined, error: TypeError: - * // x.toUpperCase is not a function at MapSubscriber.letters.map.x - * // [as project] (http://1…, hasValue: false} + * // - Notification { kind: "N", value: "A", error: undefined, hasValue: true } + * // - Notification { kind: "N", value: "B", error: undefined, hasValue: true } + * // - Notification { kind: "E", value: undefined, error: TypeError { message: x.toUpperCase is not a function }, hasValue: false } * ``` * * @see {@link Notification} @@ -58,14 +56,14 @@ export function materialize(): OperatorFunction & Observab source.subscribe( new OperatorSubscriber( subscriber, - (value) => { + value => { subscriber.next(Notification.createNext(value)); }, () => { subscriber.next(Notification.createComplete()); subscriber.complete(); }, - (err) => { + err => { subscriber.next(Notification.createError(err)); subscriber.complete(); } diff --git a/src/internal/operators/max.ts b/src/internal/operators/max.ts index 744ff8ea5e2..b3c5fcbc77e 100644 --- a/src/internal/operators/max.ts +++ b/src/internal/operators/max.ts @@ -9,34 +9,36 @@ import { isFunction } from '../util/isFunction'; * ![](max.png) * * ## Examples + * * Get the maximal value of a series of numbers + * * ```ts - * import { of } from 'rxjs'; - * import { max } from 'rxjs/operators'; + * import { of, max } from 'rxjs'; * - * of(5, 4, 7, 2, 8).pipe( - * max(), - * ) - * .subscribe(x => console.log(x)); // -> 8 + * of(5, 4, 7, 2, 8) + * .pipe(max()) + * .subscribe(x => console.log(x)); + * + * // Outputs + * // 8 * ``` * * Use a comparer function to get the maximal item - * ```typescript - * import { of } from 'rxjs'; - * import { max } from 'rxjs/operators'; - * - * interface Person { - * age: number, - * name: string - * } - *of( - * {age: 7, name: 'Foo'}, - * {age: 5, name: 'Bar'}, - * {age: 9, name: 'Beer'}, + * + * ```ts + * import { of, max } from 'rxjs'; + * + * of( + * { age: 7, name: 'Foo' }, + * { age: 5, name: 'Bar' }, + * { age: 9, name: 'Beer' } * ).pipe( - * max((a: Person, b: Person) => a.age < b.age ? -1 : 1), + * max((a, b) => a.age < b.age ? -1 : 1) * ) - * .subscribe((x: Person) => console.log(x.name)); // -> 'Beer' + * .subscribe(x => console.log(x.name)); + * + * // Outputs + * // 'Beer' * ``` * * @see {@link min} diff --git a/src/internal/operators/mergeAll.ts b/src/internal/operators/mergeAll.ts index c5fb539ff9f..9183badacb6 100644 --- a/src/internal/operators/mergeAll.ts +++ b/src/internal/operators/mergeAll.ts @@ -18,27 +18,30 @@ import { OperatorFunction, ObservableInput, ObservedValueOf } from '../types'; * a inner Observable will be immediately emitted on the output Observable. * * ## Examples + * * Spawn a new interval Observable for each click event, and blend their outputs as one Observable + * * ```ts - * import { fromEvent, interval } from 'rxjs'; - * import { map, mergeAll } from 'rxjs/operators'; + * import { fromEvent, map, interval, mergeAll } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); - * const higherOrder = clicks.pipe(map((ev) => interval(1000))); + * const higherOrder = clicks.pipe(map(() => interval(1000))); * const firstOrder = higherOrder.pipe(mergeAll()); + * * firstOrder.subscribe(x => console.log(x)); * ``` * * Count from 0 to 9 every second for each click, but only allow 2 concurrent timers + * * ```ts - * import { fromEvent, interval } from 'rxjs'; - * import { take, map, mergeAll } from 'rxjs/operators'; + * import { fromEvent, map, interval, take, mergeAll } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const higherOrder = clicks.pipe( - * map((ev) => interval(1000).pipe(take(10))), + * map(() => interval(1000).pipe(take(10))) * ); * const firstOrder = higherOrder.pipe(mergeAll(2)); + * * firstOrder.subscribe(x => console.log(x)); * ``` * diff --git a/src/internal/operators/mergeMap.ts b/src/internal/operators/mergeMap.ts index b159bda883f..6a8807618f2 100644 --- a/src/internal/operators/mergeMap.ts +++ b/src/internal/operators/mergeMap.ts @@ -39,15 +39,17 @@ export function mergeMap>( * emitting the results of this merger. * * ## Example + * * Map and flatten each letter to an Observable ticking every 1 second + * * ```ts - * import { of, interval } from 'rxjs'; - * import { mergeMap, map } from 'rxjs/operators'; + * import { of, mergeMap, interval, map } from 'rxjs'; * * const letters = of('a', 'b', 'c'); * const result = letters.pipe( - * mergeMap(x => interval(1000).pipe(map(i => x+i))), + * mergeMap(x => interval(1000).pipe(map(i => x + i))) * ); + * * result.subscribe(x => console.log(x)); * * // Results in the following: @@ -57,7 +59,7 @@ export function mergeMap>( * // a1 * // b1 * // c1 - * // continues to list a,b,c with respective ascending integers + * // continues to list a, b, c every second with respective ascending integers * ``` * * @see {@link concatMap} diff --git a/src/internal/operators/mergeMapTo.ts b/src/internal/operators/mergeMapTo.ts index d22a0c718e7..28849a2669d 100644 --- a/src/internal/operators/mergeMapTo.ts +++ b/src/internal/operators/mergeMapTo.ts @@ -29,13 +29,15 @@ export function mergeMapTo>( * single Observable, which is the output Observable. * * ## Example + * * For each click event, start an interval Observable ticking every 1 second + * * ```ts - * import { fromEvent, interval } from 'rxjs'; - * import { mergeMapTo } from 'rxjs/operators'; + * import { fromEvent, mergeMapTo, interval } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const result = clicks.pipe(mergeMapTo(interval(1000))); + * * result.subscribe(x => console.log(x)); * ``` * diff --git a/src/internal/operators/mergeScan.ts b/src/internal/operators/mergeScan.ts index 1425234c6d8..26849874f70 100644 --- a/src/internal/operators/mergeScan.ts +++ b/src/internal/operators/mergeScan.ts @@ -31,21 +31,23 @@ import { mergeInternals } from './mergeInternals'; * current emission by the source Observable. It starts with 0. * * The last parameter to the `mergeScan` is the `concurrent` value which defaults - * to Infinity. It represent the maximum number of inner Observable subscriptions + * to Infinity. It represents the maximum number of inner Observable subscriptions * at a time. * * ## Example + * * Count the number of click events + * * ```ts - * import { fromEvent, of } from 'rxjs'; - * import { mapTo, mergeScan } from 'rxjs/operators'; + * import { fromEvent, map, mergeScan, of } from 'rxjs'; * * const click$ = fromEvent(document, 'click'); - * const one$ = click$.pipe(mapTo(1)); + * const one$ = click$.pipe(map(() => 1)); * const seed = 0; * const count$ = one$.pipe( - * mergeScan((acc, one) => of(acc + one), seed), + * mergeScan((acc, one) => of(acc + one), seed) * ); + * * count$.subscribe(x => console.log(x)); * * // Results: @@ -80,7 +82,7 @@ export function mergeScan( subscriber, (value, index) => accumulator(state, value, index), concurrent, - (value) => { + value => { state = value; }, false, diff --git a/src/internal/operators/mergeWith.ts b/src/internal/operators/mergeWith.ts index 8046e141e23..b0c81426fb6 100644 --- a/src/internal/operators/mergeWith.ts +++ b/src/internal/operators/mergeWith.ts @@ -2,7 +2,7 @@ import { ObservableInputTuple, OperatorFunction } from '../types'; import { merge } from './merge'; /** - * Merge the values from all observables to an single observable result. + * Merge the values from all observables to a single observable result. * * Creates an observable, that when subscribed to, subscribes to the source * observable, and all other sources provided as arguments. All values from @@ -10,34 +10,34 @@ import { merge } from './merge'; * * When all sources complete, the resulting observable will complete. * - * When any one source errors, the resulting observable will error. + * When any source errors, the resulting observable will error. * + * ## Example * - * ### Example - * - * Joining all outputs from multiple user input event streams: + * Joining all outputs from multiple user input event streams * * ```ts - * import { fromEvent } from 'rxjs'; - * import { map, mergeWith } from 'rxjs/operators'; + * import { fromEvent, map, mergeWith } from 'rxjs'; * * const clicks$ = fromEvent(document, 'click').pipe(map(() => 'click')); * const mousemoves$ = fromEvent(document, 'mousemove').pipe(map(() => 'mousemove')); * const dblclicks$ = fromEvent(document, 'dblclick').pipe(map(() => 'dblclick')); * - * mousemoves$.pipe( - * mergeWith(clicks$, dblclicks$), - * ) - * .subscribe(x => console.log(x)); + * mousemoves$ + * .pipe(mergeWith(clicks$, dblclicks$)) + * .subscribe(x => console.log(x)); * * // result (assuming user interactions) - * // "mousemove" - * // "mousemove" - * // "mousemove" - * // "click" - * // "click" - * // "dblclick" + * // 'mousemove' + * // 'mousemove' + * // 'mousemove' + * // 'click' + * // 'click' + * // 'dblclick' * ``` + * + * @see {@link merge} + * * @param otherSources the sources to combine the current source with. * @return A function that returns an Observable that merges the values from * all given Observables. diff --git a/src/internal/operators/min.ts b/src/internal/operators/min.ts index 8a8058f8624..bef78d1c50a 100644 --- a/src/internal/operators/min.ts +++ b/src/internal/operators/min.ts @@ -9,35 +9,38 @@ import { isFunction } from '../util/isFunction'; * ![](min.png) * * ## Examples + * * Get the minimal value of a series of numbers + * * ```ts - * import { of } from 'rxjs'; - * import { min } from 'rxjs/operators'; + * import { of, min } from 'rxjs'; * - * of(5, 4, 7, 2, 8).pipe( - * min(), - * ) - * .subscribe(x => console.log(x)); // -> 2 + * of(5, 4, 7, 2, 8) + * .pipe(min()) + * .subscribe(x => console.log(x)); + * + * // Outputs + * // 2 * ``` * * Use a comparer function to get the minimal item - * ```typescript - * import { of } from 'rxjs'; - * import { min } from 'rxjs/operators'; - * - * interface Person { - * age: number, - * name: string - * } - *of( - * {age: 7, name: 'Foo'}, - * {age: 5, name: 'Bar'}, - * {age: 9, name: 'Beer'}, + * + * ```ts + * import { of, min } from 'rxjs'; + * + * of( + * { age: 7, name: 'Foo' }, + * { age: 5, name: 'Bar' }, + * { age: 9, name: 'Beer' } * ).pipe( - * min( (a: Person, b: Person) => a.age < b.age ? -1 : 1), + * min((a, b) => a.age < b.age ? -1 : 1) * ) - * .subscribe((x: Person) => console.log(x.name)); // -> 'Bar' + * .subscribe(x => console.log(x.name)); + * + * // Outputs + * // 'Bar' * ``` + * * @see {@link max} * * @param {Function} [comparer] - Optional comparer function that it will use instead of its default to compare the diff --git a/src/internal/operators/observeOn.ts b/src/internal/operators/observeOn.ts index 8f0b23c0387..3091459c891 100644 --- a/src/internal/operators/observeOn.ts +++ b/src/internal/operators/observeOn.ts @@ -5,7 +5,6 @@ import { operate } from '../util/lift'; import { OperatorSubscriber } from './OperatorSubscriber'; /** - * * Re-emits all notifications from source Observable with specified scheduler. * * Ensure a specific scheduler is used, from outside of an Observable. @@ -32,20 +31,19 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * * ## Example * - * Ensure values in subscribe are called just before browser repaint. + * Ensure values in subscribe are called just before browser repaint * * ```ts - * import { interval, animationFrameScheduler } from 'rxjs'; - * import { observeOn } from 'rxjs/operators'; + * import { interval, observeOn, animationFrameScheduler } from 'rxjs'; * * const someDiv = document.createElement('div'); * someDiv.style.cssText = 'width: 200px;background: #09c'; * document.body.appendChild(someDiv); - * const intervals = interval(10); // Intervals are scheduled - * // with async scheduler by default... + * const intervals = interval(10); // Intervals are scheduled + * // with async scheduler by default... * intervals.pipe( - * observeOn(animationFrameScheduler), // ...but we will observe on animationFrame - * ) // scheduler to ensure smooth animation. + * observeOn(animationFrameScheduler) // ...but we will observe on animationFrame + * ) // scheduler to ensure smooth animation. * .subscribe(val => { * someDiv.style.height = val + 'px'; * }); @@ -63,9 +61,9 @@ export function observeOn(scheduler: SchedulerLike, delay = 0): MonoTypeOpera source.subscribe( new OperatorSubscriber( subscriber, - (value) => executeSchedule(subscriber, scheduler, () => subscriber.next(value), delay), + value => executeSchedule(subscriber, scheduler, () => subscriber.next(value), delay), () => executeSchedule(subscriber, scheduler, () => subscriber.complete(), delay), - (err) => executeSchedule(subscriber, scheduler, () => subscriber.error(err), delay) + err => executeSchedule(subscriber, scheduler, () => subscriber.error(err), delay) ) ); }); diff --git a/src/internal/operators/onErrorResumeNext.ts b/src/internal/operators/onErrorResumeNext.ts index 9fdfcb13481..0414824d5fe 100644 --- a/src/internal/operators/onErrorResumeNext.ts +++ b/src/internal/operators/onErrorResumeNext.ts @@ -44,23 +44,28 @@ export function onErrorResumeNext( * * * ## Example + * * Subscribe to the next Observable after map fails + * * ```ts - * import { of } from 'rxjs'; - * import { onErrorResumeNext, map } from 'rxjs/operators'; + * import { of, onErrorResumeNext, map } from 'rxjs'; + * + * of(1, 2, 3, 0) + * .pipe( + * map(x => { + * if (x === 0) { + * throw Error(); + * } * - * of(1, 2, 3, 0).pipe( - * map(x => { - * if (x === 0) { throw Error(); } - * return 10 / x; - * }), - * onErrorResumeNext(of(1, 2, 3)), - * ) - * .subscribe( - * val => console.log(val), - * err => console.log(err), // Will never be called. - * () => console.log('that\'s it!') - * ); + * return 10 / x; + * }), + * onErrorResumeNext(of(1, 2, 3)) + * ) + * .subscribe({ + * next: val => console.log(val), + * error: err => console.log(err), // Will never be called. + * complete: () => console.log('that\'s it!') + * }); * * // Logs: * // 10 @@ -75,7 +80,7 @@ export function onErrorResumeNext( * @see {@link concat} * @see {@link catchError} * - * @param {...ObservableInput} nextSources Observables passed either directly or as an array. + * @param {...ObservableInput} sources Observables passed either directly or as an array. * @return A function that returns an Observable that emits values from source * Observable, but - if it errors - subscribes to the next passed Observable * and so on, until it completes or runs out of Observables. diff --git a/src/internal/operators/pairwise.ts b/src/internal/operators/pairwise.ts index b0404635631..0f579b8336f 100644 --- a/src/internal/operators/pairwise.ts +++ b/src/internal/operators/pairwise.ts @@ -18,22 +18,24 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * there is no previous value in that case. * * ## Example + * * On every click (starting from the second), emit the relative distance to the previous click + * * ```ts - * import { fromEvent } from 'rxjs'; - * import { pairwise, map } from 'rxjs/operators'; + * import { fromEvent, pairwise, map } from 'rxjs'; * - * const clicks = fromEvent(document, 'click'); + * const clicks = fromEvent(document, 'click'); * const pairs = clicks.pipe(pairwise()); * const distance = pairs.pipe( - * map(pair => { - * const x0 = pair[0].clientX; - * const y0 = pair[0].clientY; - * const x1 = pair[1].clientX; - * const y1 = pair[1].clientY; + * map(([first, second]) => { + * const x0 = first.clientX; + * const y0 = first.clientY; + * const x1 = second.clientX; + * const y1 = second.clientY; * return Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2)); - * }), + * }) * ); + * * distance.subscribe(x => console.log(x)); * ``` * @@ -48,7 +50,7 @@ export function pairwise(): OperatorFunction { let prev: T; let hasPrev = false; source.subscribe( - new OperatorSubscriber(subscriber, (value) => { + new OperatorSubscriber(subscriber, value => { const p = prev; prev = value; hasPrev && subscriber.next([p, value]); diff --git a/src/internal/operators/partition.ts b/src/internal/operators/partition.ts index 6fa9354cddc..9b02a0c0b95 100644 --- a/src/internal/operators/partition.ts +++ b/src/internal/operators/partition.ts @@ -21,15 +21,20 @@ import { UnaryFunction } from '../types'; * behaves like {@link filter} with the predicate negated. * * ## Example + * * Partition click events into those on DIV elements and those elsewhere + * * ```ts * import { fromEvent } from 'rxjs'; * import { partition } from 'rxjs/operators'; * + * const div = document.createElement('div'); + * div.style.cssText = 'width: 200px; height: 200px; background: #09c;'; + * document.body.appendChild(div); + * * const clicks = fromEvent(document, 'click'); - * const parts = clicks.pipe(partition(ev => ev.target.tagName === 'DIV')); - * const clicksOnDivs = parts[0]; - * const clicksElsewhere = parts[1]; + * const [clicksOnDivs, clicksElsewhere] = clicks.pipe(partition(ev => (ev.target).tagName === 'DIV')); + * * clicksOnDivs.subscribe(x => console.log('DIV clicked: ', x)); * clicksElsewhere.subscribe(x => console.log('Other clicked: ', x)); * ``` diff --git a/src/internal/operators/pluck.ts b/src/internal/operators/pluck.ts index aa1dc49a409..fc3ba936c78 100644 --- a/src/internal/operators/pluck.ts +++ b/src/internal/operators/pluck.ts @@ -58,13 +58,15 @@ export function pluck(...properties: string[]): OperatorFunction; * that value. * * ## Example + * * Map every click to the tagName of the clicked target element + * * ```ts - * import { fromEvent } from 'rxjs'; - * import { pluck } from 'rxjs/operators'; + * import { fromEvent, pluck } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const tagNames = clicks.pipe(pluck('target', 'tagName')); + * * tagNames.subscribe(x => console.log(x)); * ``` * @@ -81,7 +83,7 @@ export function pluck(...properties: Array): Ope if (length === 0) { throw new Error('list of properties cannot be empty.'); } - return map((x) => { + return map(x => { let currentProp: any = x; for (let i = 0; i < length; i++) { const p = currentProp?.[properties[i]]; diff --git a/src/internal/operators/publish.ts b/src/internal/operators/publish.ts index 7de67d27aa3..42d6380e29a 100644 --- a/src/internal/operators/publish.ts +++ b/src/internal/operators/publish.ts @@ -42,15 +42,15 @@ export function publish>(selector: (shared: Ob * ![](publish.png) * * ## Examples - * Make source$ hot by applying publish operator, then merge each inner observable into a single one - * and subscribe. + * + * Make `source$` hot by applying `publish` operator, then merge each inner observable into a single one + * and subscribe + * * ```ts - * import { of, zip, interval, merge } from "rxjs"; - * import { map, publish, tap } from "rxjs/operators"; + * import { zip, interval, of, map, publish, merge, tap } from 'rxjs'; * - * const source$ = zip(interval(2000), of(1, 2, 3, 4, 5, 6, 7, 8, 9)).pipe( - * map(values => values[1]) - * ); + * const source$ = zip(interval(2000), of(1, 2, 3, 4, 5, 6, 7, 8, 9)) + * .pipe(map(([, number]) => number)); * * source$ * .pipe( @@ -58,7 +58,7 @@ export function publish>(selector: (shared: Ob * merge( * multicasted$.pipe(tap(x => console.log('Stream 1:', x))), * multicasted$.pipe(tap(x => console.log('Stream 2:', x))), - * multicasted$.pipe(tap(x => console.log('Stream 3:', x))), + * multicasted$.pipe(tap(x => console.log('Stream 3:', x))) * ) * ) * ) @@ -74,6 +74,10 @@ export function publish>(selector: (shared: Ob * // Stream 3: 9 * ``` * + * @see {@link publishLast} + * @see {@link publishReplay} + * @see {@link publishBehavior} + * * @param {Function} [selector] - Optional selector function which can use the multicasted source sequence as many times * as needed, without causing multiple subscriptions to the source sequence. * Subscribers to the given source will receive all notifications of the source from the time of the subscription on. @@ -85,5 +89,5 @@ export function publish>(selector: (shared: Ob * Details: https://rxjs.dev/deprecations/multicasting */ export function publish(selector?: OperatorFunction): MonoTypeOperatorFunction | OperatorFunction { - return selector ? (source) => connect(selector)(source) : (source) => multicast(new Subject())(source); + return selector ? source => connect(selector)(source) : source => multicast(new Subject())(source); } diff --git a/src/internal/operators/publishLast.ts b/src/internal/operators/publishLast.ts index 7cde7f50d56..eb2931eee74 100644 --- a/src/internal/operators/publishLast.ts +++ b/src/internal/operators/publishLast.ts @@ -18,36 +18,37 @@ import { UnaryFunction } from '../types'; * ## Example * * ```ts - * import { interval } from 'rxjs'; - * import { publishLast, tap, take } from 'rxjs/operators'; + * import { ConnectableObservable, interval, publishLast, tap, take } from 'rxjs'; * - * const connectable = - * interval(1000) - * .pipe( - * tap(x => console.log("side effect", x)), - * take(3), - * publishLast()); + * const connectable = >interval(1000) + * .pipe( + * tap(x => console.log('side effect', x)), + * take(3), + * publishLast() + * ); * - * connectable.subscribe( - * x => console.log( "Sub. A", x), - * err => console.log("Sub. A Error", err), - * () => console.log( "Sub. A Complete")); + * connectable.subscribe({ + * next: x => console.log('Sub. A', x), + * error: err => console.log('Sub. A Error', err), + * complete: () => console.log('Sub. A Complete') + * }); * - * connectable.subscribe( - * x => console.log( "Sub. B", x), - * err => console.log("Sub. B Error", err), - * () => console.log( "Sub. B Complete")); + * connectable.subscribe({ + * next: x => console.log('Sub. B', x), + * error: err => console.log('Sub. B Error', err), + * complete: () => console.log('Sub. B Complete') + * }); * * connectable.connect(); * * // Results: - * // "side effect 0" - * // "side effect 1" - * // "side effect 2" - * // "Sub. A 2" - * // "Sub. B 2" - * // "Sub. A Complete" - * // "Sub. B Complete" + * // 'side effect 0' - after one second + * // 'side effect 1' - after two seconds + * // 'side effect 2' - after three seconds + * // 'Sub. A 2' - immediately after 'side effect 2' + * // 'Sub. B 2' + * // 'Sub. A Complete' + * // 'Sub. B Complete' * ``` * * @see {@link ConnectableObservable} @@ -68,7 +69,7 @@ import { UnaryFunction } from '../types'; */ export function publishLast(): UnaryFunction, ConnectableObservable> { // Note that this has *never* supported a selector function like `publish` and `publishReplay`. - return (source) => { + return source => { const subject = new AsyncSubject(); return new ConnectableObservable(source, () => subject); }; diff --git a/src/internal/operators/raceWith.ts b/src/internal/operators/raceWith.ts index 3953fa55cf3..6e7292982e9 100644 --- a/src/internal/operators/raceWith.ts +++ b/src/internal/operators/raceWith.ts @@ -11,18 +11,15 @@ import { identity } from '../util/identity'; * ## Example * * ```ts - * import { interval } from 'rxjs'; - * import { mapTo, raceWith } from 'rxjs/operators'; + * import { interval, map, raceWith } from 'rxjs'; * - * const obs1 = interval(1000).pipe(mapTo('fast one')); - * const obs2 = interval(3000).pipe(mapTo('medium one')); - * const obs3 = interval(5000).pipe(mapTo('slow one')); + * const obs1 = interval(7000).pipe(map(() => 'slow one')); + * const obs2 = interval(3000).pipe(map(() => 'fast one')); + * const obs3 = interval(5000).pipe(map(() => 'medium one')); * - * obs2.pipe( - * raceWith(obs3, obs1) - * ).subscribe( - * winner => console.log(winner) - * ); + * obs1 + * .pipe(raceWith(obs2, obs3)) + * .subscribe(winner => console.log(winner)); * * // Outputs * // a series of 'fast one' @@ -32,7 +29,6 @@ import { identity } from '../util/identity'; * @return A function that returns an Observable that mirrors the output of the * first Observable to emit an item. */ - export function raceWith( ...otherSources: [...ObservableInputTuple] ): OperatorFunction { diff --git a/src/internal/operators/reduce.ts b/src/internal/operators/reduce.ts index 9ff5de8566a..c9bdda0543c 100644 --- a/src/internal/operators/reduce.ts +++ b/src/internal/operators/reduce.ts @@ -30,17 +30,19 @@ export function reduce(accumulator: (acc: A | S, value: V, index: n * value is specified, the first item of the source is used as the seed. * * ## Example + * * Count the number of click events that happened in 5 seconds + * * ```ts - * import { fromEvent, interval } from 'rxjs'; - * import { reduce, takeUntil, mapTo } from 'rxjs/operators'; + * import { fromEvent, takeUntil, interval, map, reduce } from 'rxjs'; * - * const clicksInFiveSeconds = fromEvent(document, 'click').pipe( - * takeUntil(interval(5000)), - * ); - * const ones = clicksInFiveSeconds.pipe(mapTo(1)); + * const clicksInFiveSeconds = fromEvent(document, 'click') + * .pipe(takeUntil(interval(5000))); + * + * const ones = clicksInFiveSeconds.pipe(map(() => 1)); * const seed = 0; * const count = ones.pipe(reduce((acc, one) => acc + one, seed)); + * * count.subscribe(x => console.log(x)); * ``` * diff --git a/src/internal/operators/refCount.ts b/src/internal/operators/refCount.ts index 2fab3f55f8d..222a180fca2 100644 --- a/src/internal/operators/refCount.ts +++ b/src/internal/operators/refCount.ts @@ -27,18 +27,17 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * until you call its connect function. * * ```ts - * import { interval } from 'rxjs'; - * import { tap, publish, refCount } from 'rxjs/operators'; + * import { interval, tap, publish, refCount } from 'rxjs'; * * // Turn the interval observable into a ConnectableObservable (hot) * const refCountInterval = interval(400).pipe( - * tap((num) => console.log(`refCount ${num}`)), + * tap(num => console.log(`refCount ${ num }`)), * publish(), * refCount() * ); * * const publishedInterval = interval(400).pipe( - * tap((num) => console.log(`publish ${num}`)), + * tap(num => console.log(`publish ${ num }`)), * publish() * ); * @@ -46,7 +45,7 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * refCountInterval.subscribe(); * // 'refCount 0' -----> 'refCount 1' -----> etc * // All subscriptions will receive the same value and the tap (and - * // every other operator) before the publish operator will be executed + * // every other operator) before the `publish` operator will be executed * // only once per event independently of the number of subscriptions. * * publishedInterval.subscribe(); diff --git a/src/internal/operators/repeat.ts b/src/internal/operators/repeat.ts index 09da1190e8f..5bbf38c8957 100644 --- a/src/internal/operators/repeat.ts +++ b/src/internal/operators/repeat.ts @@ -17,29 +17,32 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * Note: `repeat(0)` returns an empty observable and `repeat()` will repeat forever * * ## Example + * * Repeat a message stream + * * ```ts - * import { of } from 'rxjs'; - * import { repeat } from 'rxjs/operators'; + * import { of, repeat } from 'rxjs'; * * const source = of('Repeat message'); - * const example = source.pipe(repeat(3)); - * example.subscribe(x => console.log(x)); + * const result = source.pipe(repeat(3)); + * + * result.subscribe(x => console.log(x)); * * // Results - * // Repeat message - * // Repeat message - * // Repeat message + * // 'Repeat message' + * // 'Repeat message' + * // 'Repeat message' * ``` * * Repeat 3 values, 2 times + * * ```ts - * import { interval } from 'rxjs'; - * import { repeat, take } from 'rxjs/operators'; + * import { interval, repeat, take } from 'rxjs'; * * const source = interval(1000); - * const example = source.pipe(take(3), repeat(2)); - * example.subscribe(x => console.log(x)); + * const result = source.pipe(take(3), repeat(2)); + * + * result.subscribe(x => console.log(x)); * * // Results every second * // 0 diff --git a/src/internal/operators/repeatWhen.ts b/src/internal/operators/repeatWhen.ts index 7253ade1cd4..5b83afcac52 100644 --- a/src/internal/operators/repeatWhen.ts +++ b/src/internal/operators/repeatWhen.ts @@ -15,17 +15,20 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * ![](repeatWhen.png) * * ## Example + * * Repeat a message stream on click + * * ```ts - * import { of, fromEvent } from 'rxjs'; - * import { repeatWhen } from 'rxjs/operators'; + * import { of, fromEvent, repeatWhen } from 'rxjs'; * * const source = of('Repeat message'); - * const documentClick$ = fromEvent(document, 'click'); + * const documentClicks = fromEvent(document, 'click'); * - * source.pipe(repeatWhen(() => documentClick$) - * ).subscribe(data => console.log(data)) + * const result = source.pipe(repeatWhen(() => documentClicks)); + * + * result.subscribe(data => console.log(data)) * ``` + * * @see {@link repeat} * @see {@link retry} * @see {@link retryWhen} diff --git a/src/internal/operators/retry.ts b/src/internal/operators/retry.ts index 554528c2259..8b57b29adba 100644 --- a/src/internal/operators/retry.ts +++ b/src/internal/operators/retry.ts @@ -34,39 +34,35 @@ export interface RetryConfig { * ![](retry.png) * * Any and all items emitted by the source Observable will be emitted by the resulting Observable, even those emitted - * during failed subscriptions. For example, if an Observable fails at first but emits [1, 2] then succeeds the second - * time and emits: [1, 2, 3, 4, 5] then the complete stream of emissions and notifications - * would be: [1, 2, 1, 2, 3, 4, 5, `complete`]. + * during failed subscriptions. For example, if an Observable fails at first but emits `[1, 2]` then succeeds the second + * time and emits: `[1, 2, 3, 4, 5]` then the complete stream of emissions and notifications + * would be: `[1, 2, 1, 2, 3, 4, 5, complete]`. * * ## Example + * * ```ts - * import { interval, of, throwError } from 'rxjs'; - * import { mergeMap, retry } from 'rxjs/operators'; + * import { interval, mergeMap, throwError, of, retry } from 'rxjs'; * * const source = interval(1000); - * const example = source.pipe( - * mergeMap(val => { - * if(val > 5){ - * return throwError('Error!'); - * } - * return of(val); - * }), - * //retry 2 times on error - * retry(2) + * const result = source.pipe( + * mergeMap(val => val > 5 ? throwError(() => 'Error!') : of(val)), + * retry(2) // retry 2 times on error * ); * - * const subscribe = example.subscribe({ - * next: val => console.log(val), - * error: val => console.log(`${val}: Retried 2 times then quit!`) + * result.subscribe({ + * next: value => console.log(value), + * error: err => console.log(`${ err }: Retried 2 times then quit!`) * }); * * // Output: * // 0..1..2..3..4..5.. * // 0..1..2..3..4..5.. * // 0..1..2..3..4..5.. - * // "Error!: Retried 2 times then quit!" + * // 'Error!: Retried 2 times then quit!' * ``` * + * @see {@link retryWhen} + * * @param count - Number of retry attempts before failing. * @param resetOnSuccess - When set to `true` every successful emission will reset the error count * @return A function that returns an Observable that will resubscribe to the @@ -104,7 +100,7 @@ export function retry(configOrCount: number | RetryConfig = Infinity): MonoTy innerSub = source.subscribe( new OperatorSubscriber( subscriber, - (value) => { + value => { // If we're resetting on success if (resetOnSuccess) { soFar = 0; @@ -113,7 +109,7 @@ export function retry(configOrCount: number | RetryConfig = Infinity): MonoTy }, // Completions are passed through to consumer. undefined, - (err) => { + err => { if (soFar++ < count) { // We are still under our retry count const resub = () => { diff --git a/src/internal/operators/retryWhen.ts b/src/internal/operators/retryWhen.ts index 5d5f15c5470..348468df154 100644 --- a/src/internal/operators/retryWhen.ts +++ b/src/internal/operators/retryWhen.ts @@ -17,42 +17,44 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * Retry an observable sequence on error based on custom criteria. * * ## Example + * * ```ts - * import { timer, interval } from 'rxjs'; - * import { map, tap, retryWhen, delayWhen } from 'rxjs/operators'; + * import { interval, map, retryWhen, tap, delayWhen, timer } from 'rxjs'; * * const source = interval(1000); - * const example = source.pipe( - * map(val => { - * if (val > 5) { + * const result = source.pipe( + * map(value => { + * if (value > 5) { * // error will be picked up by retryWhen - * throw val; + * throw value; * } - * return val; + * return value; * }), * retryWhen(errors => * errors.pipe( * // log error message - * tap(val => console.log(`Value ${val} was too high!`)), + * tap(value => console.log(`Value ${ value } was too high!`)), * // restart in 5 seconds - * delayWhen(val => timer(val * 1000)) + * delayWhen(value => timer(value * 1000)) * ) * ) * ); * - * const subscribe = example.subscribe(val => console.log(val)); + * result.subscribe(value => console.log(value)); * * // results: - * // 0 - * // 1 - * // 2 - * // 3 - * // 4 - * // 5 - * // "Value 6 was too high!" - * // --Wait 5 seconds then repeat + * // 0 + * // 1 + * // 2 + * // 3 + * // 4 + * // 5 + * // 'Value 6 was too high!' + * // - Wait 5 seconds then repeat * ``` * + * @see {@link retry} + * * @param {function(errors: Observable): Observable} notifier - Receives an Observable of notifications with which a * user can `complete` or `error`, aborting the retry. * @return A function that returns an Observable that mirrors the source @@ -66,7 +68,7 @@ export function retryWhen(notifier: (errors: Observable) => Observable { innerSub = source.subscribe( - new OperatorSubscriber(subscriber, undefined, undefined, (err) => { + new OperatorSubscriber(subscriber, undefined, undefined, err => { if (!errors$) { errors$ = new Subject(); notifier(errors$).subscribe( diff --git a/src/internal/operators/sample.ts b/src/internal/operators/sample.ts index 7ce877f9179..5f7233637e0 100644 --- a/src/internal/operators/sample.ts +++ b/src/internal/operators/sample.ts @@ -20,14 +20,16 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * as the output Observable is subscribed. * * ## Example - * On every click, sample the most recent "seconds" timer + * + * On every click, sample the most recent `seconds` timer + * * ```ts - * import { fromEvent, interval } from 'rxjs'; - * import { sample } from 'rxjs/operators'; + * import { fromEvent, interval, sample } from 'rxjs'; * * const seconds = interval(1000); * const clicks = fromEvent(document, 'click'); * const result = seconds.pipe(sample(clicks)); + * * result.subscribe(x => console.log(x)); * ``` * @@ -47,7 +49,7 @@ export function sample(notifier: Observable): MonoTypeOperatorFunction { + new OperatorSubscriber(subscriber, value => { hasValue = true; lastValue = value; }) diff --git a/src/internal/operators/sampleTime.ts b/src/internal/operators/sampleTime.ts index 0a5dda28308..6558fa03ab4 100644 --- a/src/internal/operators/sampleTime.ts +++ b/src/internal/operators/sampleTime.ts @@ -20,13 +20,15 @@ import { interval } from '../observable/interval'; * the output Observable is subscribed. * * ## Example + * * Every second, emit the most recent click at most once + * * ```ts - * import { fromEvent } from 'rxjs'; - * import { sampleTime } from 'rxjs/operators'; + * import { fromEvent, sampleTime } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const result = clicks.pipe(sampleTime(1000)); + * * result.subscribe(x => console.log(x)); * ``` * diff --git a/src/internal/operators/scan.ts b/src/internal/operators/scan.ts index 12429943866..e97e967e598 100644 --- a/src/internal/operators/scan.ts +++ b/src/internal/operators/scan.ts @@ -28,15 +28,14 @@ export function scan(accumulator: (acc: A | S, value: V, index: number) * 3. Emit `state`. * 4. Next value arrives, let `value = nextValue`, go to 2. * - * ## Example + * ## Examples * * An average of previous numbers. This example shows how * not providing a `seed` can prime the stream with the * first value from the source. * * ```ts - * import { interval, of } from 'rxjs'; - * import { scan, map } from 'rxjs/operators'; + * import { of, scan, map } from 'rxjs'; * * const numbers$ = of(1, 2, 3); * @@ -51,21 +50,18 @@ export function scan(accumulator: (acc: A | S, value: V, index: number) * .subscribe(console.log); * ``` * - * ## Example - * * The Fibonacci sequence. This example shows how you can use - * a seed to prime accumulation process. Also... you know... Fibinacci. + * a seed to prime accumulation process. Also... you know... Fibonacci. * So important to like, computers and stuff that its whiteboarded * in job interviews. Now you can show them the Rx version! (Please don't, haha) * * ```ts - * import { interval } from 'rxjs'; - * import { scan, map, startWith } from 'rxjs/operators'; + * import { interval, scan, map, startWith } from 'rxjs'; * * const firstTwoFibs = [0, 1]; - * // An endless stream of Fibonnaci numbers. - * const fibonnaci$ = interval(1000).pipe( - * // Scan to get the fibonnaci numbers (after 0, 1) + * // An endless stream of Fibonacci numbers. + * const fibonacci$ = interval(1000).pipe( + * // Scan to get the fibonacci numbers (after 0, 1) * scan(([a, b]) => [b, a + b], firstTwoFibs), * // Get the second number in the tuple, it's the one you calculated * map(([, n]) => n), @@ -73,10 +69,9 @@ export function scan(accumulator: (acc: A | S, value: V, index: number) * startWith(...firstTwoFibs) * ); * - * fibonnaci$.subscribe(console.log); + * fibonacci$.subscribe(console.log); * ``` * - * * @see {@link expand} * @see {@link mergeScan} * @see {@link reduce} diff --git a/src/internal/operators/sequenceEqual.ts b/src/internal/operators/sequenceEqual.ts index 9d1d7be6429..e9d035094f0 100644 --- a/src/internal/operators/sequenceEqual.ts +++ b/src/internal/operators/sequenceEqual.ts @@ -21,10 +21,11 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * completes or emits after the other completes, the returned observable will never complete. * * ## Example - * figure out if the Konami code matches + * + * Figure out if the Konami code matches + * * ```ts - * import { from, fromEvent } from 'rxjs'; - * import { sequenceEqual, bufferCount, mergeMap, map } from 'rxjs/operators'; + * import { from, fromEvent, map, bufferCount, mergeMap, sequenceEqual } from 'rxjs'; * * const codes = from([ * 'ArrowUp', @@ -40,12 +41,10 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * 'Enter', // no start key, clearly. * ]); * - * const keys = fromEvent(document, 'keyup').pipe(map(e => e.code)); + * const keys = fromEvent(document, 'keyup').pipe(map(e => e.code)); * const matches = keys.pipe( * bufferCount(11, 1), - * mergeMap( - * last11 => from(last11).pipe(sequenceEqual(codes)), - * ), + * mergeMap(last11 => from(last11).pipe(sequenceEqual(codes))) * ); * matches.subscribe(matched => console.log('Successful cheat at Contra? ', matched)); * ``` diff --git a/src/internal/operators/share.ts b/src/internal/operators/share.ts index 433649149b1..0df2169a82a 100644 --- a/src/internal/operators/share.ts +++ b/src/internal/operators/share.ts @@ -68,45 +68,54 @@ export function share(options: ShareConfig): MonoTypeOperatorFunction; * ![](share.png) * * ## Example - * Generate new multicast Observable from the source Observable value + * + * Generate new multicast Observable from the `source` Observable value + * * ```ts - * import { interval } from 'rxjs'; - * import { share, map } from 'rxjs/operators'; - * - * const source = interval(1000) - * .pipe( - * map((x: number) => { - * console.log('Processing: ', x); - * return x*x; - * }), - * share() + * import { interval, tap, map, take, share } from 'rxjs'; + * + * const source = interval(1000).pipe( + * tap(x => console.log('Processing: ', x)), + * map(x => x * x), + * take(6), + * share() * ); * * source.subscribe(x => console.log('subscription 1: ', x)); * source.subscribe(x => console.log('subscription 2: ', x)); * * // Logs: - * // Processing: 0 - * // subscription 1: 0 - * // subscription 2: 0 - * // Processing: 1 - * // subscription 1: 1 - * // subscription 2: 1 - * // Processing: 2 - * // subscription 1: 4 - * // subscription 2: 4 - * // Processing: 3 - * // subscription 1: 9 - * // subscription 2: 9 - * // ... and so on + * // Processing: 0 + * // subscription 1: 0 + * // subscription 2: 0 + * // Processing: 1 + * // subscription 1: 1 + * // subscription 2: 1 + * // Processing: 2 + * // subscription 1: 4 + * // subscription 2: 4 + * // Processing: 3 + * // subscription 1: 9 + * // subscription 2: 9 + * // Processing: 4 + * // subscription 1: 16 + * // subscription 2: 16 + * // Processing: 5 + * // subscription 1: 25 + * // subscription 2: 25 * ``` * * ## Example with notifier factory: Delayed reset + * * ```ts - * import { interval, timer } from 'rxjs'; - * import { share, take } from 'rxjs/operators'; + * import { interval, take, share, timer } from 'rxjs'; * - * const source = interval(1000).pipe(take(3), share({ resetOnRefCountZero: () => timer(1000) })); + * const source = interval(1000).pipe( + * take(3), + * share({ + * resetOnRefCountZero: () => timer(1000) + * }) + * ); * * const subscriptionOne = source.subscribe(x => console.log('subscription 1: ', x)); * setTimeout(() => subscriptionOne.unsubscribe(), 1300); @@ -128,7 +137,8 @@ export function share(options: ShareConfig): MonoTypeOperatorFunction; * // subscription 3: 2 * ``` * - * @see {@link api/index/function/interval} + * @see {@link shareReplay} + * @see {@link interval} * @see {@link map} * * @return A function that returns an Observable that mirrors the source. @@ -144,7 +154,7 @@ export function share(options: ShareConfig = {}): MonoTypeOperatorFunction // _operator function_ is called when the complete pipeline is composed via a // call to a source observable's `pipe` method - not when the static `pipe` // function is called. - return (wrapperSource) => { + return wrapperSource => { let connection: SafeSubscriber | null = null; let resetConnection: Subscription | null = null; let subject: SubjectLike | null = null; @@ -210,8 +220,8 @@ export function share(options: ShareConfig = {}): MonoTypeOperatorFunction // those situations we want connection to be already-assigned so that we // don't create another connection to the source. connection = new SafeSubscriber({ - next: (value) => dest.next(value), - error: (err) => { + next: value => dest.next(value), + error: err => { hasErrored = true; cancelReset(); resetConnection = handleReset(reset, resetOnError, err); diff --git a/src/internal/operators/shareReplay.ts b/src/internal/operators/shareReplay.ts index 49c59e9314e..d3575befe3a 100644 --- a/src/internal/operators/shareReplay.ts +++ b/src/internal/operators/shareReplay.ts @@ -38,43 +38,69 @@ export function shareReplay(bufferSize?: number, windowTime?: number, schedul * If `refCount` is false on the other hand, the source will not be unsubscribed meaning that the inner * `ReplaySubject` will still be subscribed to the source (and potentially run for ever). * - * ## Example + * ## Examples + * + * Example with a third subscriber coming late to the party + * * ```ts - * import { interval } from 'rxjs'; - * import { shareReplay, take } from 'rxjs/operators'; + * import { interval, shareReplay, take } from 'rxjs'; * - * const obs$ = interval(1000); - * const shared$ = obs$.pipe( - * take(4), + * const shared$ = interval(2000).pipe( + * take(6), * shareReplay(3) * ); * shared$.subscribe(x => console.log('sub A: ', x)); * shared$.subscribe(y => console.log('sub B: ', y)); + * setTimeout(() => { + * shared$.subscribe(y => console.log('sub C: ', y)); + * }, 11000); * + * // Logs: + * // (after ~2000 ms) + * // sub A: 0 + * // sub B: 0 + * // (after ~4000 ms) + * // sub A: 1 + * // sub B: 1 + * // (after ~6000 ms) + * // sub A: 2 + * // sub B: 2 + * // (after ~8000 ms) + * // sub A: 3 + * // sub B: 3 + * // (after ~10000 ms) + * // sub A: 4 + * // sub B: 4 + * // (after ~11000 ms, sub C gets the last 3 values) + * // sub C: 2 + * // sub C: 3 + * // sub C: 4 + * // (after ~12000 ms) + * // sub A: 5 + * // sub B: 5 + * // sub C: 5 * ``` * - * ## Example for refCount usage + * Example for `refCount` usage + * * ```ts - * import { interval, Observable, defer } from 'rxjs'; - * import { shareReplay, take, tap, finalize } from 'rxjs/operators'; - * - * const log = (source: Observable, name: string) => defer(() => { - * console.log(`${name}: subscribed`); - * return source.pipe( - * tap({ - * next: value => console.log(`${name}: ${value}`), - * complete: () => console.log(`${name}: complete`) - * }), - * finalize(() => console.log(`${name}: unsubscribed`)) - * ); - * }); - * - * const obs$ = log(interval(1000), 'source'); - * - * const shared$ = log(obs$.pipe( - * shareReplay({bufferSize: 1, refCount: true }), - * take(2), - * ), 'shared'); + * import { Observable, tap, interval, shareReplay, take } from 'rxjs'; + * + * const log = (name: string, source: Observable) => source.pipe( + * tap({ + * subscribe: () => console.log(`${ name }: subscribed`), + * next: value => console.log(`${ name }: ${ value }`), + * complete: () => console.log(`${ name }: completed`), + * finalize: () => console.log(`${ name }: unsubscribed`) + * }) + * ); + * + * const obs$ = log('source', interval(1000)); + * + * const shared$ = log('shared', obs$.pipe( + * shareReplay({ bufferSize: 1, refCount: true }), + * take(2) + * )); * * shared$.subscribe(x => console.log('sub A: ', x)); * shared$.subscribe(y => console.log('sub B: ', y)); @@ -91,11 +117,11 @@ export function shareReplay(bufferSize?: number, windowTime?: number, schedul * // source: 1 * // shared: 1 * // sub A: 1 - * // shared: complete <-- take(2) completes the subscription for sub A + * // shared: completed <-- take(2) completes the subscription for sub A * // shared: unsubscribed <-- reference count = 1 * // shared: 1 * // sub B: 1 - * // shared: complete <-- take(2) completes the subscription for sub B + * // shared: completed <-- take(2) completes the subscription for sub B * // shared: unsubscribed <-- reference count = 0 * // source: unsubscribed <-- replaySubject unsubscribes from source observable because the reference count dropped to 0 and refCount is true * @@ -138,6 +164,6 @@ export function shareReplay( connector: () => new ReplaySubject(bufferSize, windowTime, scheduler), resetOnError: true, resetOnComplete: false, - resetOnRefCountZero: refCount + resetOnRefCountZero: refCount, }); } diff --git a/src/internal/operators/single.ts b/src/internal/operators/single.ts index e4151a6aa11..f6071cc2c01 100644 --- a/src/internal/operators/single.ts +++ b/src/internal/operators/single.ts @@ -28,11 +28,10 @@ export function single(predicate?: (value: T, index: number, source: Observab * * ## Example * - * Expect only name beginning with 'B': + * Expect only `name` beginning with `'B'` * * ```ts - * import { of } from 'rxjs'; - * import { single } from 'rxjs/operators'; + * import { of, single } from 'rxjs'; * * const source1 = of( * { name: 'Ben' }, @@ -41,11 +40,10 @@ export function single(predicate?: (value: T, index: number, source: Observab * { name: 'Lily' } * ); * - * source1.pipe( - * single(x => x.name.startsWith('B')) - * ) - * .subscribe(x => console.log(x)); - * // Emits "Ben" + * source1 + * .pipe(single(x => x.name.startsWith('B'))) + * .subscribe(x => console.log(x)); + * // Emits 'Ben' * * * const source2 = of( @@ -55,10 +53,9 @@ export function single(predicate?: (value: T, index: number, source: Observab * { name: 'Lincoln' } * ); * - * source2.pipe( - * single(x => x.name.startsWith('B')) - * ) - * .subscribe(x => console.log(x)); + * source2 + * .pipe(single(x => x.name.startsWith('B'))) + * .subscribe({ error: err => console.error(err) }); * // Error emitted: SequenceError('Too many values match') * * @@ -69,10 +66,9 @@ export function single(predicate?: (value: T, index: number, source: Observab * { name: 'Lincoln' } * ); * - * source3.pipe( - * single(x => x.name.startsWith('B')) - * ) - * .subscribe(x => console.log(x)); + * source3 + * .pipe(single(x => x.name.startsWith('B'))) + * .subscribe({ error: err => console.error(err) }); * // Error emitted: NotFoundError('No values match') * ``` * @@ -85,7 +81,7 @@ export function single(predicate?: (value: T, index: number, source: Observab * callback if the Observable completes before any `next` notification was sent. * @throws {SequenceError} Delivers a SequenceError if more than one value is emitted that matches the * provided predicate. If no predicate is provided, will deliver a SequenceError if more - * that one value comes from the source + * than one value comes from the source * @param {Function} predicate - A predicate function to evaluate items emitted by the source Observable. * @return A function that returns an Observable that emits the single item * emitted by the source Observable that matches the predicate. @@ -99,7 +95,7 @@ export function single(predicate?: (value: T, index: number, source: Observab source.subscribe( new OperatorSubscriber( subscriber, - (value) => { + value => { seenValue = true; if (!predicate || predicate(value, index++, source)) { hasValue && subscriber.error(new SequenceError('Too many matching values')); diff --git a/src/internal/operators/skip.ts b/src/internal/operators/skip.ts index 02f8fc0930c..76e3eff2dfc 100644 --- a/src/internal/operators/skip.ts +++ b/src/internal/operators/skip.ts @@ -10,17 +10,19 @@ import { filter } from './filter'; * an error if skip count is equal or more than the actual number of emits and source raises an error. * * ## Example + * * Skip the values before the emission + * * ```ts - * import { interval } from 'rxjs'; - * import { skip } from 'rxjs/operators'; + * import { interval, skip } from 'rxjs'; * - * //emit every half second + * // emit every half second * const source = interval(500); - * //skip the first 10 emitted values - * const example = source.pipe(skip(10)); - * //output: 10...11...12...13........ - * const subscribe = example.subscribe(val => console.log(val)); + * // skip the first 10 emitted values + * const result = source.pipe(skip(10)); + * + * result.subscribe(value => console.log(value)); + * // output: 10...11...12...13... * ``` * * @see {@link last} diff --git a/src/internal/operators/skipLast.ts b/src/internal/operators/skipLast.ts index 20e652920d2..3b2b8370470 100644 --- a/src/internal/operators/skipLast.ts +++ b/src/internal/operators/skipLast.ts @@ -25,8 +25,7 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * Skip the last 2 values of an observable with many values * * ```ts - * import { of } from 'rxjs'; - * import { skipLast } from 'rxjs/operators'; + * import { of, skipLast } from 'rxjs'; * * const numbers = of(1, 2, 3, 4, 5); * const skipLastTwo = numbers.pipe(skipLast(2)); @@ -59,7 +58,7 @@ export function skipLast(skipCount: number): MonoTypeOperatorFunction { // the index of the current value when it arrives. let seen = 0; source.subscribe( - new OperatorSubscriber(subscriber, (value) => { + new OperatorSubscriber(subscriber, value => { // Get the index of the value we have right now // relative to all other values we've seen, then // increment `seen`. This ensures we've moved to diff --git a/src/internal/operators/skipUntil.ts b/src/internal/operators/skipUntil.ts index b17bdb96b8c..6982855ea5c 100644 --- a/src/internal/operators/skipUntil.ts +++ b/src/internal/operators/skipUntil.ts @@ -8,7 +8,7 @@ import { noop } from '../util/noop'; /** * Returns an Observable that skips items emitted by the source Observable until a second Observable emits an item. * - * The `skipUntil` operator causes the observable stream to skip the emission of values ​​until the passed in observable emits the first value. + * The `skipUntil` operator causes the observable stream to skip the emission of values until the passed in observable emits the first value. * This can be particularly useful in combination with user interactions, responses of http requests or waiting for specific times to pass by. * * ![](skipUntil.png) @@ -20,11 +20,10 @@ import { noop } from '../util/noop'; * * ## Example * - * In the following example, all emitted values ​​of the interval observable are skipped until the user clicks anywhere within the page. + * In the following example, all emitted values of the interval observable are skipped until the user clicks anywhere within the page * * ```ts - * import { interval, fromEvent } from 'rxjs'; - * import { skipUntil } from 'rxjs/operators'; + * import { interval, fromEvent, skipUntil } from 'rxjs'; * * const intervalObservable = interval(1000); * const click = fromEvent(document, 'click'); @@ -34,9 +33,14 @@ import { noop } from '../util/noop'; * ); * // clicked at 4.6s. output: 5...6...7...8........ or * // clicked at 7.3s. output: 8...9...10..11....... - * const subscribe = emitAfterClick.subscribe(value => console.log(value)); + * emitAfterClick.subscribe(value => console.log(value)); * ``` * + * @see {@link last} + * @see {@link skip} + * @see {@link skipWhile} + * @see {@link skipLast} + * * @param {Observable} notifier - The second Observable that has to emit an item before the source Observable's elements begin to * be mirrored by the resulting Observable. * @return A function that returns an Observable that skips items from the @@ -58,6 +62,6 @@ export function skipUntil(notifier: Observable): MonoTypeOperatorFunctio innerFrom(notifier).subscribe(skipSubscriber); - source.subscribe(new OperatorSubscriber(subscriber, (value) => taking && subscriber.next(value))); + source.subscribe(new OperatorSubscriber(subscriber, value => taking && subscriber.next(value))); }); } diff --git a/src/internal/operators/skipWhile.ts b/src/internal/operators/skipWhile.ts index 18367c15cc0..ae44ff46328 100644 --- a/src/internal/operators/skipWhile.ts +++ b/src/internal/operators/skipWhile.ts @@ -16,26 +16,28 @@ export function skipWhile(predicate: (value: T, index: number) => boolean): M * It can also be skipped using index. Once the predicate is true, it will not be called again. * * ## Example - * Using Value: Skip some super heroes + * + * Skip some super heroes + * * ```ts - * import { from } from 'rxjs'; - * import { skipWhile } from 'rxjs/operators'; + * import { of, skipWhile } from 'rxjs'; * - * const source = from(['Green Arrow', 'SuperMan', 'Flash', 'SuperGirl', 'Black Canary']) + * const source = of('Green Arrow', 'SuperMan', 'Flash', 'SuperGirl', 'Black Canary'); * // Skip the heroes until SuperGirl - * const example = source.pipe(skipWhile((hero) => hero !== 'SuperGirl')); + * const example = source.pipe(skipWhile(hero => hero !== 'SuperGirl')); * // output: SuperGirl, Black Canary - * example.subscribe((femaleHero) => console.log(femaleHero)); + * example.subscribe(femaleHero => console.log(femaleHero)); * ``` - * Using Index: Skip value from the array until index 5 + * + * Skip values from the array until index 5 + * * ```ts - * import { from } from 'rxjs'; - * import { skipWhile } from 'rxjs/operators'; + * import { of, skipWhile } from 'rxjs'; * - * const source = from([1, 2, 3, 4, 5, 6, 7, 9, 10]); + * const source = of(1, 2, 3, 4, 5, 6, 7, 9, 10); * const example = source.pipe(skipWhile((_, i) => i !== 5)); * // output: 6, 7, 9, 10 - * example.subscribe((val) => console.log(val)); + * example.subscribe(value => console.log(value)); * ``` * * @see {@link last} @@ -52,7 +54,7 @@ export function skipWhile(predicate: (value: T, index: number) => boolean): M let taking = false; let index = 0; source.subscribe( - new OperatorSubscriber(subscriber, (value) => (taking || (taking = !predicate(value, index++))) && subscriber.next(value)) + new OperatorSubscriber(subscriber, value => (taking || (taking = !predicate(value, index++))) && subscriber.next(value)) ); }); } diff --git a/src/internal/operators/startWith.ts b/src/internal/operators/startWith.ts index b639a16f7f1..8c11ddb52bd 100644 --- a/src/internal/operators/startWith.ts +++ b/src/internal/operators/startWith.ts @@ -34,8 +34,7 @@ export function startWith(...values: A): * Emit a value when a timer starts. * * ```ts - * import { timer } from 'rxjs'; - * import { startWith, map } from 'rxjs/operators'; + * import { timer, map, startWith } from 'rxjs'; * * timer(1000) * .pipe( @@ -45,8 +44,8 @@ export function startWith(...values: A): * .subscribe(x => console.log(x)); * * // results: - * // "timer start" - * // "timer emit" + * // 'timer start' + * // 'timer emit' * ``` * * @param values Items you want the modified Observable to emit first. diff --git a/src/internal/operators/subscribeOn.ts b/src/internal/operators/subscribeOn.ts index 0e905932212..17240d04888 100644 --- a/src/internal/operators/subscribeOn.ts +++ b/src/internal/operators/subscribeOn.ts @@ -33,11 +33,10 @@ import { operate } from '../util/lift'; * * Both Observable `a` and `b` will emit their values directly and synchronously once they are subscribed to. * - * If we instead use the `subscribeOn` operator declaring that we want to use the {@link asyncScheduler} for values emited by Observable `a`: + * If we instead use the `subscribeOn` operator declaring that we want to use the {@link asyncScheduler} for values emitted by Observable `a`: * * ```ts - * import { of, merge, asyncScheduler } from 'rxjs'; - * import { subscribeOn } from 'rxjs/operators'; + * import { of, subscribeOn, asyncScheduler, merge } from 'rxjs'; * * const a = of(1, 2, 3).pipe(subscribeOn(asyncScheduler)); * const b = of(4, 5, 6); diff --git a/src/internal/operators/switchAll.ts b/src/internal/operators/switchAll.ts index 9e854dda6a0..293b45c63f5 100644 --- a/src/internal/operators/switchAll.ts +++ b/src/internal/operators/switchAll.ts @@ -19,15 +19,15 @@ import { identity } from '../util/identity'; * if there are any. * * ## Examples + * * Spawn a new interval observable for each click event, but for every new - * click, cancel the previous interval and subscribe to the new one. + * click, cancel the previous interval and subscribe to the new one * * ```ts - * import { fromEvent, interval } from 'rxjs'; - * import { switchAll, map, tap } from 'rxjs/operators'; + * import { fromEvent, tap, map, interval, switchAll } from 'rxjs'; * * const clicks = fromEvent(document, 'click').pipe(tap(() => console.log('click'))); - * const source = clicks.pipe(map((ev) => interval(1000))); + * const source = clicks.pipe(map(() => interval(1000))); * * source.pipe( * switchAll() @@ -60,7 +60,6 @@ import { identity } from '../util/identity'; * Observable into a first-order Observable producing values only from the most * recent Observable sequence. */ - export function switchAll>(): OperatorFunction> { return switchMap(identity); } diff --git a/src/internal/operators/switchMap.ts b/src/internal/operators/switchMap.ts index 3c8cd1fa3f7..83f648b6c3f 100644 --- a/src/internal/operators/switchMap.ts +++ b/src/internal/operators/switchMap.ts @@ -39,12 +39,13 @@ export function switchMap>( * subsequent inner Observables. * * ## Example + * * Generate new Observable according to source Observable values - * ```typescript - * import { of } from 'rxjs'; - * import { switchMap } from 'rxjs/operators'; * - * const switched = of(1, 2, 3).pipe(switchMap((x: number) => of(x, x ** 2, x ** 3))); + * ```ts + * import { of, switchMap } from 'rxjs'; + * + * const switched = of(1, 2, 3).pipe(switchMap(x => of(x, x ** 2, x ** 3))); * switched.subscribe(x => console.log(x)); * // outputs * // 1 @@ -53,16 +54,18 @@ export function switchMap>( * // 2 * // 4 * // 8 - * // ... and so on + * // 3 + * // 9 + * // 27 * ``` * * Restart an interval Observable on every click event + * * ```ts - * import { fromEvent, interval } from 'rxjs'; - * import { switchMap } from 'rxjs/operators'; + * import { fromEvent, switchMap, interval } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); - * const result = clicks.pipe(switchMap((ev) => interval(1000))); + * const result = clicks.pipe(switchMap(() => interval(1000))); * result.subscribe(x => console.log(x)); * ``` * @@ -72,7 +75,7 @@ export function switchMap>( * @see {@link switchAll} * @see {@link switchMapTo} * - * @param {function(value: T, ?index: number): ObservableInput} project A function + * @param {function(value: T, index: number): ObservableInput} project A function * that, when applied to an item emitted by the source Observable, returns an * Observable. * @return A function that returns an Observable that emits the result of @@ -97,7 +100,7 @@ export function switchMap>( source.subscribe( new OperatorSubscriber( subscriber, - (value) => { + value => { // Cancel the previous inner subscription if there was one innerSubscriber?.unsubscribe(); let innerIndex = 0; @@ -109,7 +112,7 @@ export function switchMap>( // When we get a new inner value, next it through. Note that this is // handling the deprecate result selector here. This is because with this architecture // it ends up being smaller than using the map operator. - (innerValue) => subscriber.next(resultSelector ? resultSelector(value, innerValue, outerIndex, innerIndex++) : innerValue), + innerValue => subscriber.next(resultSelector ? resultSelector(value, innerValue, outerIndex, innerIndex++) : innerValue), () => { // The inner has completed. Null out the inner subcriber to // free up memory and to signal that we have no inner subscription diff --git a/src/internal/operators/switchMapTo.ts b/src/internal/operators/switchMapTo.ts index 5025d4ce2b9..a3ff875fe9b 100644 --- a/src/internal/operators/switchMapTo.ts +++ b/src/internal/operators/switchMapTo.ts @@ -32,10 +32,11 @@ export function switchMapTo>( * `innerObservable`. * * ## Example - * Rerun an interval Observable on every click event + * + * Restart an interval Observable on every click event + * * ```ts - * import { fromEvent, interval } from 'rxjs'; - * import { switchMapTo } from 'rxjs/operators'; + * import { fromEvent, switchMapTo, interval } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const result = clicks.pipe(switchMapTo(interval(1000))); diff --git a/src/internal/operators/take.ts b/src/internal/operators/take.ts index e8bc9ba9312..f11d9b38d8f 100644 --- a/src/internal/operators/take.ts +++ b/src/internal/operators/take.ts @@ -17,10 +17,11 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * source completes. * * ## Example + * * Take the first 5 seconds of an infinite 1-second interval Observable + * * ```ts - * import { interval } from 'rxjs'; - * import { take } from 'rxjs/operators'; + * import { interval, take } from 'rxjs'; * * const intervalCount = interval(1000); * const takeFive = intervalCount.pipe(take(5)); @@ -51,7 +52,7 @@ export function take(count: number): MonoTypeOperatorFunction { : operate((source, subscriber) => { let seen = 0; source.subscribe( - new OperatorSubscriber(subscriber, (value) => { + new OperatorSubscriber(subscriber, value => { // Increment the number of values we have seen, // then check it against the allowed count to see // if we are still letting values through. diff --git a/src/internal/operators/takeLast.ts b/src/internal/operators/takeLast.ts index 3e3697ce605..91b5ce05e83 100644 --- a/src/internal/operators/takeLast.ts +++ b/src/internal/operators/takeLast.ts @@ -25,8 +25,7 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * Take the last 3 values of an Observable with many values * * ```ts - * import { range } from 'rxjs'; - * import { takeLast } from 'rxjs/operators'; + * import { range, takeLast } from 'rxjs'; * * const many = range(1, 100); * const lastThree = many.pipe(takeLast(3)); @@ -55,7 +54,7 @@ export function takeLast(count: number): MonoTypeOperatorFunction { source.subscribe( new OperatorSubscriber( subscriber, - (value) => { + value => { // Add the most recent value onto the end of our buffer. buffer.push(value); // If our buffer is now larger than the number of values we diff --git a/src/internal/operators/takeUntil.ts b/src/internal/operators/takeUntil.ts index 3c594a04207..7e37cc52c21 100644 --- a/src/internal/operators/takeUntil.ts +++ b/src/internal/operators/takeUntil.ts @@ -20,10 +20,11 @@ import { noop } from '../util/noop'; * then `takeUntil` will pass all values. * * ## Example + * * Tick every second until the first click happens + * * ```ts - * import { fromEvent, interval } from 'rxjs'; - * import { takeUntil } from 'rxjs/operators'; + * import { interval, fromEvent, takeUntil } from 'rxjs'; * * const source = interval(1000); * const clicks = fromEvent(document, 'click'); diff --git a/src/internal/operators/takeWhile.ts b/src/internal/operators/takeWhile.ts index 1ae3f0e8c0c..919375add88 100644 --- a/src/internal/operators/takeWhile.ts +++ b/src/internal/operators/takeWhile.ts @@ -30,12 +30,13 @@ export function takeWhile(predicate: (value: T, index: number) => boolean, in * Observable and completes the output Observable. * * ## Example + * * Emit click events only while the clientX property is greater than 200 + * * ```ts - * import { fromEvent } from 'rxjs'; - * import { takeWhile } from 'rxjs/operators'; + * import { fromEvent, takeWhile } from 'rxjs'; * - * const clicks = fromEvent(document, 'click'); + * const clicks = fromEvent(document, 'click'); * const result = clicks.pipe(takeWhile(ev => ev.clientX > 200)); * result.subscribe(x => console.log(x)); * ``` @@ -58,7 +59,7 @@ export function takeWhile(predicate: (value: T, index: number) => boolean, in return operate((source, subscriber) => { let index = 0; source.subscribe( - new OperatorSubscriber(subscriber, (value) => { + new OperatorSubscriber(subscriber, value => { const result = predicate(value, index++); (result || inclusive) && subscriber.next(value); !result && subscriber.complete(); diff --git a/src/internal/operators/tap.ts b/src/internal/operators/tap.ts index 364d4ca3eb4..8f6f9fcc815 100644 --- a/src/internal/operators/tap.ts +++ b/src/internal/operators/tap.ts @@ -43,14 +43,14 @@ export function tap( * in your observable `pipe`, log out the notifications as they are emitted by the source returned by the previous * operation. * - * ## Example + * ## Examples + * * Check a random number before it is handled. Below is an observable that will use a random number between 0 and 1, - * and emit "big" or "small" depending on the size of that number. But we wanted to log what the original number + * and emit `'big'` or `'small'` depending on the size of that number. But we wanted to log what the original number * was, so we have added a `tap(console.log)`. * * ```ts - * import { of } from 'rxjs'; - * import { tap, map } from 'rxjs/operators'; + * import { of, tap, map } from 'rxjs'; * * of(Math.random()).pipe( * tap(console.log), @@ -58,46 +58,39 @@ export function tap( * ).subscribe(console.log); * ``` * - * ## Example * Using `tap` to analyze a value and force an error. Below is an observable where in our system we only * want to emit numbers 3 or less we get from another source. We can force our observable to error * using `tap`. * * ```ts - * import { of } from 'rxjs'; - * import { tap } from 'rxjs/operators'; + * import { of, tap } from 'rxjs'; * - * const source = of(1, 2, 3, 4, 5) + * const source = of(1, 2, 3, 4, 5); * * source.pipe( - * tap(n => { - * if (n > 3) { - * throw new TypeError(`Value ${n} is greater than 3`) - * } - * }) + * tap(n => { + * if (n > 3) { + * throw new TypeError(`Value ${ n } is greater than 3`); + * } + * }) * ) - * .subscribe(console.log); + * .subscribe({ next: console.log, error: err => console.log(err.message) }); * ``` * - * ## Example * We want to know when an observable completes before moving on to the next observable. The system - * below will emit a random series of `"X"` characters from 3 different observables in sequence. The + * below will emit a random series of `'X'` characters from 3 different observables in sequence. The * only way we know when one observable completes and moves to the next one, in this case, is because - * we have added a `tap` with the side-effect of logging to console. + * we have added a `tap` with the side effect of logging to console. * * ```ts - * import { of, interval } from 'rxjs'; - * import { tap, map, concatMap, take } from 'rxjs/operators'; - * + * import { of, concatMap, interval, take, map, tap } from 'rxjs'; * * of(1, 2, 3).pipe( - * concatMap(n => interval(1000).pipe( - * take(Math.round(Math.random() * 10)), - * map(() => 'X'), - * tap({ - * complete: () => console.log(`Done with ${n}`) - * }) - * )) + * concatMap(n => interval(1000).pipe( + * take(Math.round(Math.random() * 10)), + * map(() => 'X'), + * tap({ complete: () => console.log(`Done with ${ n }`) }) + * )) * ) * .subscribe(console.log); * ``` @@ -132,7 +125,7 @@ export function tap( source.subscribe( new OperatorSubscriber( subscriber, - (value) => { + value => { tapObserver.next?.(value); subscriber.next(value); }, @@ -141,7 +134,7 @@ export function tap( tapObserver.complete?.(); subscriber.complete(); }, - (err) => { + err => { isUnsub = false; tapObserver.error?.(err); subscriber.error(err); diff --git a/src/internal/operators/throttle.ts b/src/internal/operators/throttle.ts index 454d67b6fcf..25ae03924a5 100644 --- a/src/internal/operators/throttle.ts +++ b/src/internal/operators/throttle.ts @@ -35,13 +35,15 @@ export const defaultThrottleConfig: ThrottleConfig = { * next source value. * * ## Example + * * Emit clicks at a rate of at most one click per second + * * ```ts - * import { fromEvent, interval } from 'rxjs'; - * import { throttle } from 'rxjs/operators'; + * import { fromEvent, throttle, interval } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); - * const result = clicks.pipe(throttle(ev => interval(1000))); + * const result = clicks.pipe(throttle(() => interval(1000))); + * * result.subscribe(x => console.log(x)); * ``` * @@ -108,7 +110,7 @@ export function throttle( // but legal - an already-closed subscription will be assigned to // throttled, so the subscription's closed property needs to be checked, // too. - (value) => { + value => { hasValue = true; sendValue = value; !(throttled && !throttled.closed) && (leading ? send() : startThrottle(value)); diff --git a/src/internal/operators/throttleTime.ts b/src/internal/operators/throttleTime.ts index 8dc17e6f9f6..54461bf6a1b 100644 --- a/src/internal/operators/throttleTime.ts +++ b/src/internal/operators/throttleTime.ts @@ -23,41 +23,41 @@ import { timer } from '../observable/timer'; * * ## Examples * - * #### Limit click rate + * ### Limit click rate * * Emit clicks at a rate of at most one click per second + * * ```ts - * import { fromEvent } from 'rxjs'; - * import { throttleTime } from 'rxjs/operators'; + * import { fromEvent, throttleTime } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const result = clicks.pipe(throttleTime(1000)); + * * result.subscribe(x => console.log(x)); * ``` * - * #### Double Click + * ### Double Click * * The following example only emits clicks which happen within a subsequent * delay of 400ms of the previous click. This for example can emulate a double * click. It makes use of the `trailing` parameter of the throttle configuration. * * ```ts - * import { fromEvent, asyncScheduler } from 'rxjs'; - * import { throttleTime, withLatestFrom } from 'rxjs/operators'; + * import { fromEvent, throttleTime, asyncScheduler } from 'rxjs'; * - * // defaultThottleConfig = { leading: true, trailing: false } + * // defaultThrottleConfig = { leading: true, trailing: false }; * const throttleConfig = { * leading: false, * trailing: true - * } + * }; * * const click = fromEvent(document, 'click'); * const doubleClick = click.pipe( * throttleTime(400, asyncScheduler, throttleConfig) * ); * - * doubleClick.subscribe((throttleValue: Event) => { - * console.log(`Double-clicked! Timestamp: ${throttleValue.timeStamp}`); + * doubleClick.subscribe(event => { + * console.log(`Double-clicked! Timestamp: ${ event.timeStamp }`); * }); * ``` * diff --git a/src/internal/operators/throwIfEmpty.ts b/src/internal/operators/throwIfEmpty.ts index b7ab366598f..d0f0b455670 100644 --- a/src/internal/operators/throwIfEmpty.ts +++ b/src/internal/operators/throwIfEmpty.ts @@ -11,21 +11,25 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * ![](throwIfEmpty.png) * * ## Example + * + * Throw an error if the document wasn't clicked within 1 second + * * ```ts - * import { fromEvent, timer } from 'rxjs'; - * import { throwIfEmpty, takeUntil } from 'rxjs/operators'; + * import { fromEvent, takeUntil, timer, throwIfEmpty } from 'rxjs'; * * const click$ = fromEvent(document, 'click'); * * click$.pipe( * takeUntil(timer(1000)), - * throwIfEmpty( - * () => new Error('the document was not clicked within 1 second') - * ), + * throwIfEmpty(() => new Error('The document was not clicked within 1 second')) * ) * .subscribe({ - * next() { console.log('The button was clicked'); }, - * error(err) { console.error(err); } + * next() { + * console.log('The document was clicked'); + * }, + * error(err) { + * console.error(err.message); + * } * }); * ``` * @@ -41,7 +45,7 @@ export function throwIfEmpty(errorFactory: () => any = defaultErrorFactory): source.subscribe( new OperatorSubscriber( subscriber, - (value) => { + value => { hasValue = true; subscriber.next(value); }, diff --git a/src/internal/operators/timeInterval.ts b/src/internal/operators/timeInterval.ts index 8fa26950b6d..9becdc79dda 100644 --- a/src/internal/operators/timeInterval.ts +++ b/src/internal/operators/timeInterval.ts @@ -1,12 +1,11 @@ import { Observable } from '../Observable'; -import { async } from '../scheduler/async'; +import { asyncScheduler } from '../scheduler/async'; import { SchedulerLike, OperatorFunction } from '../types'; import { scan } from './scan'; import { defer } from '../observable/defer'; import { map } from './map'; /** - * * Emits an object containing the current value, and the time that has * passed between emitting the current value and the previous value, which is * calculated by using the provided `scheduler`'s `now()` method to retrieve @@ -19,41 +18,33 @@ import { map } from './map'; * * ![](timeInterval.png) * - * ## Examples + * ## Example + * * Emit interval between current value with the last value * * ```ts - * import { interval } from "rxjs"; - * import { timeInterval, timeout } from "rxjs/operators"; + * import { interval, timeInterval } from 'rxjs'; * * const seconds = interval(1000); * - * seconds.pipe(timeInterval()) - * .subscribe({ - * next: value => console.log(value), - * error: err => console.log(err), - * }); - * - * seconds.pipe(timeout(900)) - * .subscribe({ - * next: value => console.log(value), - * error: err => console.log(err), - * }); + * seconds + * .pipe(timeInterval()) + * .subscribe(value => console.log(value)); * * // NOTE: The values will never be this precise, * // intervals created with `interval` or `setInterval` * // are non-deterministic. * - * // {value: 0, interval: 1000} - * // {value: 1, interval: 1000} - * // {value: 2, interval: 1000} + * // { value: 0, interval: 1000 } + * // { value: 1, interval: 1000 } + * // { value: 2, interval: 1000 } * ``` * * @param {SchedulerLike} [scheduler] Scheduler used to get the current time. * @return A function that returns an Observable that emits information about * value and interval. */ -export function timeInterval(scheduler: SchedulerLike = async): OperatorFunction> { +export function timeInterval(scheduler: SchedulerLike = asyncScheduler): OperatorFunction> { return (source: Observable) => defer(() => { return source.pipe( diff --git a/src/internal/operators/timeout.ts b/src/internal/operators/timeout.ts index d3d8fdcdf45..18a7622eb02 100644 --- a/src/internal/operators/timeout.ts +++ b/src/internal/operators/timeout.ts @@ -74,19 +74,19 @@ export interface TimeoutErrorCtor { } /** - * An error thrown by the {@link operators/timeout} operator. + * An error thrown by the {@link timeout} operator. * * Provided so users can use as a type and do quality comparisons. * We recommend you do not subclass this or create instances of this class directly. * If you have need of a error representing a timeout, you should * create your own error class and use that. * - * @see {@link operators/timeout} + * @see {@link timeout} * * @class TimeoutError */ export const TimeoutError: TimeoutErrorCtor = createErrorClass( - (_super) => + _super => function TimeoutErrorImpl(this: any, info: TimeoutInfo | null = null) { _super(this); this.message = 'Timeout has occurred'; @@ -116,52 +116,48 @@ export const TimeoutError: TimeoutErrorCtor = createErrorClass( * `first` is _not_ provided, the value from `each` will be used to check timeout conditions for the arrival of the first * value and all subsequent values. If `first` _is_ provided, `each` will only be use to check all values after the first. * - * ### Example + * ## Examples * * Emit a custom error if there is too much time between values * * ```ts - * import { interval, throwError } from 'rxjs'; - * import { timeout } from 'rxjs/operators'; + * import { interval, timeout, throwError } from 'rxjs'; * * class CustomTimeoutError extends Error { * constructor() { - * super('It was too slow'); - * this.name = 'CustomTimeoutError'; + * super('It was too slow'); + * this.name = 'CustomTimeoutError'; * } * } * * const slow$ = interval(900); * * slow$.pipe( - * timeout({ - * each: 1000, - * with: () => throwError(new CustomTimeoutError()) - * }) + * timeout({ + * each: 1000, + * with: () => throwError(() => new CustomTimeoutError()) + * }) * ) * .subscribe({ - * error: console.error - * }) + * error: console.error + * }); * ``` * - * ### Example - * * Switch to a faster observable if your source is slow. * * ```ts - * import { interval, throwError } from 'rxjs'; - * import { timeout } from 'rxjs/operators'; + * import { interval, timeout } from 'rxjs'; * * const slow$ = interval(900); * const fast$ = interval(500); * * slow$.pipe( - * timeout({ - * each: 1000, - * with: () => fast$, - * }) + * timeout({ + * each: 1000, + * with: () => fast$, + * }) * ) - * .subscribe(console.log) + * .subscribe(console.log); * ``` * @param config The configuration for the timeout. */ @@ -200,66 +196,63 @@ export function timeout, M = unknown>( * In this case, you would check the error for `instanceof TimeoutError` to validate that the error was indeed from `timeout`, and * not from some other source. If it's not from `timeout`, you should probably rethrow it if you're in a `catchError`. * - * - * ### Example + * ## Examples * * Emit a {@link TimeoutError} if the first value, and _only_ the first value, does not arrive within 5 seconds * * ```ts - * import { interval } from 'rxjs'; - * import { timeout } from 'rxjs/operators'; + * import { interval, timeout } from 'rxjs'; * * // A random interval that lasts between 0 and 10 seconds per tick - * const source$ = interval(Math.round(Math.random() * 10000)); + * const source$ = interval(Math.round(Math.random() * 10_000)); * * source$.pipe( - * timeout({ first: 5000 }) + * timeout({ first: 5_000 }) * ) - * .subscribe(console.log); + * .subscribe({ + * next: console.log, + * error: console.error + * }); * ``` * - * ### Example - * * Emit a {@link TimeoutError} if the source waits longer than 5 seconds between any two values or the first value * and subscription. * * ```ts - * import { timer } from 'rxjs'; - * import { timeout, expand } from 'rxjs/operators'; + * import { timer, timeout, expand } from 'rxjs'; * - * const getRandomTime = () => Math.round(Math.random() * 10000); + * const getRandomTime = () => Math.round(Math.random() * 10_000); * * // An observable that waits a random amount of time between each delivered value - * const source$ = timer(getRandomTime()).pipe( - * expand(() => timer(getRandomTime())) - * ) - * - * source$.pipe( - * timeout({ each: 5000 }) - * ) - * .subscribe(console.log); + * const source$ = timer(getRandomTime()) + * .pipe(expand(() => timer(getRandomTime()))); + * + * source$ + * .pipe(timeout({ each: 5_000 })) + * .subscribe({ + * next: console.log, + * error: console.error + * }); * ``` * - * ### Example - * - * Emit a {@link TimeoutError} if the the source does not emit before 7 seconds, _or_ if the source waits longer than + * Emit a {@link TimeoutError} if the source does not emit before 7 seconds, _or_ if the source waits longer than * 5 seconds between any two values after the first. * * ```ts - * import { timer } from 'rxjs'; - * import { timeout, expand } from 'rxjs/operators'; + * import { timer, timeout, expand } from 'rxjs'; * - * const getRandomTime = () => Math.round(Math.random() * 10000); + * const getRandomTime = () => Math.round(Math.random() * 10_000); * * // An observable that waits a random amount of time between each delivered value - * const source$ = timer(getRandomTime()).pipe( - * expand(() => timer(getRandomTime())) - * ) - * - * source$.pipe( - * timeout({ first: 7000, each: 5000 }) - * ) - * .subscribe(console.log); + * const source$ = timer(getRandomTime()) + * .pipe(expand(() => timer(getRandomTime()))); + * + * source$ + * .pipe(timeout({ first: 7_000, each: 5_000 })) + * .subscribe({ + * next: console.log, + * error: console.error + * }); * ``` */ export function timeout(config: Omit, 'with'>): OperatorFunction; @@ -300,6 +293,8 @@ export function timeout(each: number, scheduler?: SchedulerLike): MonoTypeOpe * * ![](timeout.png) * + * @see {@link timeoutWith} + * * @return A function that returns an Observable that mirrors behaviour of the * source Observable, unless timeout happens when it throws an error. */ diff --git a/src/internal/operators/timeoutWith.ts b/src/internal/operators/timeoutWith.ts index 0870d8013ac..7f9078f3015 100644 --- a/src/internal/operators/timeoutWith.ts +++ b/src/internal/operators/timeoutWith.ts @@ -20,7 +20,7 @@ import { timeout } from './timeout'; export function timeoutWith(dueBy: Date, switchTo: ObservableInput, scheduler?: SchedulerLike): OperatorFunction; /** - * When the passed timespan ellapses before the source emits any given value, it will unsubscribe from the source, + * When the passed timespan elapses before the source emits any given value, it will unsubscribe from the source, * and switch the subscription to another observable. * * Used to switch to a different observable if your source is being slow @@ -32,47 +32,44 @@ export function timeoutWith(dueBy: Date, switchTo: ObservableInput, sch * - You want to emit a custom error rather than the {@link TimeoutError} emitted * by the default usage of {@link timeout}. * - * ## Example + * ## Examples * * Fallback to a faster observable * * ```ts - * import { interval } from 'rxjs'; - * import { timeoutWith } from 'rxjs/operators'; + * import { interval, timeoutWith } from 'rxjs'; * * const slow$ = interval(1000); * const faster$ = interval(500); * - * slow$.pipe( - * timeoutWith(900, faster$) - * ) - * .subscribe(console.log) + * slow$ + * .pipe(timeoutWith(900, faster$)) + * .subscribe(console.log); * ``` * - * ### Example - * * Emit your own custom timeout error * * ```ts - * import { interval, throwError } from 'rxjs'; - * import { timeoutWith } from 'rxjs/operators'; + * import { interval, timeoutWith, throwError } from 'rxjs'; * * class CustomTimeoutError extends Error { * constructor() { - * super('It was too slow'); - * this.name = 'CustomTimeoutError'; + * super('It was too slow'); + * this.name = 'CustomTimeoutError'; * } * } * - * const slow = interval(1000); + * const slow$ = interval(1000); * - * slow$.pipe( - * timeoutWith(900, throwError(new CustomTimeoutError())) - * ) - * .subscribe({ - * error: console.error - * }) + * slow$ + * .pipe(timeoutWith(900, throwError(() => new CustomTimeoutError()))) + * .subscribe({ + * error: err => console.error(err.message) + * }); * ``` + * + * @see {@link timeout} + * * @param waitFor The time allowed between values from the source before timeout is triggered. * @param switchTo The observable to switch to when timeout occurs. * @param scheduler The scheduler to use with time-related operations within this operator. Defaults to {@link asyncScheduler} diff --git a/src/internal/operators/timestamp.ts b/src/internal/operators/timestamp.ts index efecad7fb2d..bb388de0de5 100644 --- a/src/internal/operators/timestamp.ts +++ b/src/internal/operators/timestamp.ts @@ -8,24 +8,23 @@ import { map } from './map'; * The `timestamp` operator maps the *source* observable stream to an object of type * `{value: T, timestamp: R}`. The properties are generically typed. The `value` property contains the value * and type of the *source* observable. The `timestamp` is generated by the schedulers `now` function. By - * default it uses the *async* scheduler which simply returns `Date.now()` (milliseconds since 1970/01/01 + * default, it uses the `asyncScheduler` which simply returns `Date.now()` (milliseconds since 1970/01/01 * 00:00:00:000) and therefore is of type `number`. * * ![](timestamp.png) * * ## Example * - * In this example there is a timestamp attached to the documents click event. + * In this example there is a timestamp attached to the document's click events * * ```ts - * import { fromEvent } from 'rxjs'; - * import { timestamp } from 'rxjs/operators'; + * import { fromEvent, timestamp } from 'rxjs'; * * const clickWithTimestamp = fromEvent(document, 'click').pipe( * timestamp() * ); * - * // Emits data of type {value: MouseEvent, timestamp: number} + * // Emits data of type { value: PointerEvent, timestamp: number } * clickWithTimestamp.subscribe(data => { * console.log(data); * }); @@ -36,5 +35,5 @@ import { map } from './map'; * each item emitted by the source Observable indicating when it was emitted. */ export function timestamp(timestampProvider: TimestampProvider = dateTimestampProvider): OperatorFunction> { - return map((value: T) => ({ value, timestamp: timestampProvider.now()})); + return map((value: T) => ({ value, timestamp: timestampProvider.now() })); } diff --git a/src/internal/operators/toArray.ts b/src/internal/operators/toArray.ts index bab880281f3..8c60aced2b2 100644 --- a/src/internal/operators/toArray.ts +++ b/src/internal/operators/toArray.ts @@ -15,10 +15,10 @@ const arrReducer = (arr: any[], value: any) => (arr.push(value), arr); * the array containing all emissions. When the source Observable errors no * array will be emitted. * - * ## Example + * ## Example + * * ```ts - * import { interval } from 'rxjs'; - * import { toArray, take } from 'rxjs/operators'; + * import { interval, take, toArray } from 'rxjs'; * * const source = interval(1000); * const example = source.pipe( @@ -26,7 +26,7 @@ const arrReducer = (arr: any[], value: any) => (arr.push(value), arr); * toArray() * ); * - * const subscribe = example.subscribe(val => console.log(val)); + * example.subscribe(value => console.log(value)); * * // output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] * ``` @@ -39,6 +39,6 @@ export function toArray(): OperatorFunction { // reducer process, we have to escapulate the creation of the initial // array within this `operate` function. return operate((source, subscriber) => { - reduce(arrReducer, [] as T[])(source).subscribe(subscriber) + reduce(arrReducer, [] as T[])(source).subscribe(subscriber); }); } diff --git a/src/internal/operators/window.ts b/src/internal/operators/window.ts index 3be79a09cfc..7cef7a877dc 100644 --- a/src/internal/operators/window.ts +++ b/src/internal/operators/window.ts @@ -21,20 +21,22 @@ import { noop } from '../util/noop'; * Observable, the output is a higher-order Observable. * * ## Example + * * In every window of 1 second each, emit at most 2 click events + * * ```ts - * import { fromEvent, interval } from 'rxjs'; - * import { window, mergeAll, map, take } from 'rxjs/operators'; + * import { fromEvent, interval, window, map, take, mergeAll } from 'rxjs'; * - * const clicks = fromEvent(document, 'click'); - * const sec = interval(1000); - * const result = clicks.pipe( - * window(sec), - * map(win => win.pipe(take(2))), // each window has at most 2 emissions - * mergeAll(), // flatten the Observable-of-Observables - * ); - * result.subscribe(x => console.log(x)); + * const clicks = fromEvent(document, 'click'); + * const sec = interval(1000); + * const result = clicks.pipe( + * window(sec), + * map(win => win.pipe(take(2))), // take at most 2 emissions from each window + * mergeAll() // flatten the Observable-of-Observables + * ); + * result.subscribe(x => console.log(x)); * ``` + * * @see {@link windowCount} * @see {@link windowTime} * @see {@link windowToggle} @@ -61,7 +63,7 @@ export function window(windowBoundaries: Observable): OperatorFunction windowSubject?.next(value), + value => windowSubject?.next(value), () => { windowSubject.complete(); subscriber.complete(); diff --git a/src/internal/operators/windowCount.ts b/src/internal/operators/windowCount.ts index d01e09335e9..1206a515ce9 100644 --- a/src/internal/operators/windowCount.ts +++ b/src/internal/operators/windowCount.ts @@ -23,10 +23,11 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * with size `windowSize`. * * ## Examples + * * Ignore every 3rd click event, starting from the first one + * * ```ts - * import { fromEvent } from 'rxjs'; - * import { windowCount, map, mergeAll, skip } from 'rxjs/operators'; + * import { fromEvent, windowCount, map, skip, mergeAll } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const result = clicks.pipe( @@ -38,14 +39,14 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * ``` * * Ignore every 3rd click event, starting from the third one + * * ```ts - * import { fromEvent } from 'rxjs'; - * import { windowCount, mergeAll } from 'rxjs/operators'; + * import { fromEvent, windowCount, mergeAll } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const result = clicks.pipe( * windowCount(2, 3), - * mergeAll(), // flatten the Observable-of-Observables + * mergeAll() // flatten the Observable-of-Observables * ); * result.subscribe(x => console.log(x)); * ``` @@ -113,7 +114,7 @@ export function windowCount(windowSize: number, startWindowEvery: number = 0) } subscriber.complete(); }, - (err) => { + err => { while (windows.length > 0) { windows.shift()!.error(err); } diff --git a/src/internal/operators/windowTime.ts b/src/internal/operators/windowTime.ts index 4301e616ad4..f88ddb0c374 100644 --- a/src/internal/operators/windowTime.ts +++ b/src/internal/operators/windowTime.ts @@ -21,6 +21,7 @@ export function windowTime( maxWindowSize: number, scheduler?: SchedulerLike ): OperatorFunction>; + /** * Branch out the source Observable values as a nested Observable periodically * in time. @@ -44,43 +45,44 @@ export function windowTime( * `windowTimeSpan` and `windowCreationInterval` arguments. * * ## Examples + * * In every window of 1 second each, emit at most 2 click events + * * ```ts - * import { fromEvent } from 'rxjs'; - * import { windowTime, map, mergeAll, take } from 'rxjs/operators'; + * import { fromEvent, windowTime, map, take, mergeAll } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const result = clicks.pipe( * windowTime(1000), - * map(win => win.pipe(take(2))), // each window has at most 2 emissions - * mergeAll(), // flatten the Observable-of-Observables + * map(win => win.pipe(take(2))), // take at most 2 emissions from each window + * mergeAll() // flatten the Observable-of-Observables * ); * result.subscribe(x => console.log(x)); * ``` * * Every 5 seconds start a window 1 second long, and emit at most 2 click events per window + * * ```ts - * import { fromEvent } from 'rxjs'; - * import { windowTime, map, mergeAll, take } from 'rxjs/operators'; + * import { fromEvent, windowTime, map, take, mergeAll } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const result = clicks.pipe( * windowTime(1000, 5000), - * map(win => win.pipe(take(2))), // each window has at most 2 emissions - * mergeAll(), // flatten the Observable-of-Observables + * map(win => win.pipe(take(2))), // take at most 2 emissions from each window + * mergeAll() // flatten the Observable-of-Observables * ); * result.subscribe(x => console.log(x)); * ``` * - * Same as example above but with maxWindowCount instead of take + * Same as example above but with `maxWindowCount` instead of `take` + * * ```ts - * import { fromEvent } from 'rxjs'; - * import { windowTime, mergeAll } from 'rxjs/operators'; + * import { fromEvent, windowTime, mergeAll } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const result = clicks.pipe( - * windowTime(1000, 5000, 2), // each window has still at most 2 emissions - * mergeAll(), // flatten the Observable-of-Observables + * windowTime(1000, 5000, 2), // take at most 2 emissions from each window + * mergeAll() // flatten the Observable-of-Observables * ); * result.subscribe(x => console.log(x)); * ``` @@ -175,16 +177,16 @@ export function windowTime(windowTimeSpan: number, ...otherArgs: any[]): Oper subscriber, (value: T) => { // Notify all windows of the value. - loop((record) => { + loop(record => { record.window.next(value); // If the window is over the max size, we need to close it. maxWindowSize <= ++record.seen && closeWindow(record); }); }, // Complete the windows and the downstream subscriber and clean up. - () => terminate((consumer) => consumer.complete()), + () => terminate(consumer => consumer.complete()), // Notify the windows and the downstream subscriber of the error and clean up. - (err) => terminate((consumer) => consumer.error(err)) + err => terminate(consumer => consumer.error(err)) ) ); diff --git a/src/internal/operators/windowToggle.ts b/src/internal/operators/windowToggle.ts index ce1c3958b85..4299a9daca3 100644 --- a/src/internal/operators/windowToggle.ts +++ b/src/internal/operators/windowToggle.ts @@ -25,10 +25,11 @@ import { arrRemove } from '../util/arrRemove'; * `closingSelector` emits an item. * * ## Example + * * Every other second, emit the click events from the next 500ms + * * ```ts - * import { fromEvent, interval, EMPTY } from 'rxjs'; - * import { windowToggle, mergeAll } from 'rxjs/operators'; + * import { fromEvent, interval, windowToggle, EMPTY, mergeAll } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const openings = interval(1000); @@ -71,7 +72,7 @@ export function windowToggle( innerFrom(openings).subscribe( new OperatorSubscriber( subscriber, - (openValue) => { + openValue => { const window = new Subject(); windows.push(window); const closingSubscription = new Subscription(); diff --git a/src/internal/operators/windowWhen.ts b/src/internal/operators/windowWhen.ts index c8ae1556de0..080c71dd5c8 100644 --- a/src/internal/operators/windowWhen.ts +++ b/src/internal/operators/windowWhen.ts @@ -23,16 +23,17 @@ import { innerFrom } from '../observable/innerFrom'; * window is opened immediately when subscribing to the output Observable. * * ## Example + * * Emit only the first two clicks events in every window of [1-5] random seconds + * * ```ts - * import { fromEvent, interval } from 'rxjs'; - * import { windowWhen, map, mergeAll, take } from 'rxjs/operators'; + * import { fromEvent, windowWhen, interval, map, take, mergeAll } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const result = clicks.pipe( * windowWhen(() => interval(1000 + Math.random() * 4000)), - * map(win => win.pipe(take(2))), // each window has at most 2 emissions - * mergeAll() // flatten the Observable-of-Observables + * map(win => win.pipe(take(2))), // take at most 2 emissions from each window + * mergeAll() // flatten the Observable-of-Observables * ); * result.subscribe(x => console.log(x)); * ``` @@ -104,7 +105,7 @@ export function windowWhen(closingSelector: () => ObservableInput): Oper source.subscribe( new OperatorSubscriber( subscriber, - (value) => window!.next(value), + value => window!.next(value), () => { // The source completed, close the window and complete. window!.complete(); diff --git a/src/internal/operators/withLatestFrom.ts b/src/internal/operators/withLatestFrom.ts index 9e4bc97a176..0ca81712832 100644 --- a/src/internal/operators/withLatestFrom.ts +++ b/src/internal/operators/withLatestFrom.ts @@ -30,10 +30,11 @@ export function withLatestFrom( * emit at least one value before the output Observable will emit a value. * * ## Example + * * On every click event, emit an array with the latest timer event plus the click event + * * ```ts - * import { fromEvent, interval } from 'rxjs'; - * import { withLatestFrom } from 'rxjs/operators'; + * import { fromEvent, interval, withLatestFrom } from 'rxjs'; * * const clicks = fromEvent(document, 'click'); * const timer = interval(1000); @@ -76,7 +77,7 @@ export function withLatestFrom(...inputs: any[]): OperatorFunction { + value => { otherValues[i] = value; if (!ready && !hasValue[i]) { // If we're not ready yet, flag to show this observable has emitted. @@ -97,7 +98,7 @@ export function withLatestFrom(...inputs: any[]): OperatorFunction { + new OperatorSubscriber(subscriber, value => { if (ready) { // We have at least one value from the other sources. Go ahead and emit. const values = [value, ...otherValues];