diff --git a/CHANGELOG.md b/CHANGELOG.md index 24f377f893..a61a1b53f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## [7.5.2](https://github.com/reactivex/rxjs/compare/7.5.1...7.5.2) (2022-01-11) + +### Bug Fixes + +- operators that ignore input values now use `unknown` rather than `any`, which should resolve issues with eslint no-unsafe-argument ([#6738](https://github.com/reactivex/rxjs/issues/6738)) ([67cb317](https://github.com/reactivex/rxjs/commit/67cb317a7a6b9fdbd3d2e8fdbc2ac9ac7e57179c)), closes [#6536](https://github.com/reactivex/rxjs/issues/6536) +- **ajax:** crossDomain flag deprecated and properly reported to consumers ([#6710](https://github.com/reactivex/rxjs/issues/6710)) ([7fd0575](https://github.com/reactivex/rxjs/commit/7fd05756c595dddb288b732b00a90fcfb2a9080a)), closes [#6663](https://github.com/reactivex/rxjs/issues/6663) + ## [7.5.1](https://github.com/reactivex/rxjs/compare/7.5.0...7.5.1) (2021-12-28) ### Bug Fixes diff --git a/README.md b/README.md index 24de33ab0b..910eef75ab 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# RxJS Logo RxJS: Reactive Extensions For JavaScript +# RxJS Logo RxJS: Reactive Extensions For JavaScript ![CI](https://github.com/reactivex/rxjs/workflows/CI/badge.svg) [![npm version](https://badge.fury.io/js/rxjs.svg)](http://badge.fury.io/js/rxjs) @@ -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/api_guard/dist/types/index.d.ts b/api_guard/dist/types/index.d.ts index 7cfc595493..1a14efdf38 100644 --- a/api_guard/dist/types/index.d.ts +++ b/api_guard/dist/types/index.d.ts @@ -108,8 +108,8 @@ export declare function concatMap>(project: (v export declare function concatMap>(project: (value: T, index: number) => O, resultSelector: undefined): OperatorFunction>; export declare function concatMap>(project: (value: T, index: number) => O, resultSelector: (outerValue: T, innerValue: ObservedValueOf, outerIndex: number, innerIndex: number) => R): OperatorFunction; -export declare function concatMapTo>(observable: O): OperatorFunction>; -export declare function concatMapTo>(observable: O, resultSelector: undefined): OperatorFunction>; +export declare function concatMapTo>(observable: O): OperatorFunction>; +export declare function concatMapTo>(observable: O, resultSelector: undefined): OperatorFunction>; export declare function concatMapTo>(observable: O, resultSelector: (outerValue: T, innerValue: ObservedValueOf, outerIndex: number, innerIndex: number) => R): OperatorFunction; export declare function concatWith(...otherSources: [...ObservableInputTuple]): OperatorFunction; @@ -314,7 +314,7 @@ export declare type Head = ((...args: X) => any) exten export declare function identity(x: T): T; -export declare function ignoreElements(): OperatorFunction; +export declare function ignoreElements(): OperatorFunction; export declare function iif(condition: () => boolean, trueResult: ObservableInput, falseResult: ObservableInput): Observable; @@ -340,7 +340,7 @@ export declare function lastValueFrom(source: Observable): Promise; export declare function map(project: (value: T, index: number) => R): OperatorFunction; export declare function map(project: (this: A, value: T, index: number) => R, thisArg: A): OperatorFunction; -export declare function mapTo(value: R): OperatorFunction; +export declare function mapTo(value: R): OperatorFunction; export declare function mapTo(value: R): OperatorFunction; export declare function materialize(): OperatorFunction & ObservableNotification>; @@ -358,7 +358,7 @@ export declare function mergeMap>(project: (va export declare function mergeMap>(project: (value: T, index: number) => O, resultSelector: undefined, concurrent?: number): OperatorFunction>; export declare function mergeMap>(project: (value: T, index: number) => O, resultSelector: (outerValue: T, innerValue: ObservedValueOf, outerIndex: number, innerIndex: number) => R, concurrent?: number): OperatorFunction; -export declare function mergeMapTo>(innerObservable: O, concurrent?: number): OperatorFunction>; +export declare function mergeMapTo>(innerObservable: O, concurrent?: number): OperatorFunction>; export declare function mergeMapTo>(innerObservable: O, resultSelector: (outerValue: T, innerValue: ObservedValueOf, outerIndex: number, innerIndex: number) => R, concurrent?: number): OperatorFunction; export declare function mergeScan(accumulator: (acc: R, value: T, index: number) => ObservableInput, seed: R, concurrent?: number): OperatorFunction; @@ -729,8 +729,8 @@ export declare function switchMap>(project: (v export declare function switchMap>(project: (value: T, index: number) => O, resultSelector: undefined): OperatorFunction>; export declare function switchMap>(project: (value: T, index: number) => O, resultSelector: (outerValue: T, innerValue: ObservedValueOf, outerIndex: number, innerIndex: number) => R): OperatorFunction; -export declare function switchMapTo>(observable: O): OperatorFunction>; -export declare function switchMapTo>(observable: O, resultSelector: undefined): OperatorFunction>; +export declare function switchMapTo>(observable: O): OperatorFunction>; +export declare function switchMapTo>(observable: O, resultSelector: undefined): OperatorFunction>; export declare function switchMapTo>(observable: O, resultSelector: (outerValue: T, innerValue: ObservedValueOf, outerIndex: number, innerIndex: number) => R): OperatorFunction; export declare function switchScan>(accumulator: (acc: R, value: T, index: number) => O, seed: R): OperatorFunction>; diff --git a/api_guard/dist/types/operators/index.d.ts b/api_guard/dist/types/operators/index.d.ts index 034286c140..4d673c5b08 100644 --- a/api_guard/dist/types/operators/index.d.ts +++ b/api_guard/dist/types/operators/index.d.ts @@ -45,8 +45,8 @@ export declare function concatMap>(project: (v export declare function concatMap>(project: (value: T, index: number) => O, resultSelector: undefined): OperatorFunction>; export declare function concatMap>(project: (value: T, index: number) => O, resultSelector: (outerValue: T, innerValue: ObservedValueOf, outerIndex: number, innerIndex: number) => R): OperatorFunction; -export declare function concatMapTo>(observable: O): OperatorFunction>; -export declare function concatMapTo>(observable: O, resultSelector: undefined): OperatorFunction>; +export declare function concatMapTo>(observable: O): OperatorFunction>; +export declare function concatMapTo>(observable: O, resultSelector: undefined): OperatorFunction>; export declare function concatMapTo>(observable: O, resultSelector: (outerValue: T, innerValue: ObservedValueOf, outerIndex: number, innerIndex: number) => R): OperatorFunction; export declare function concatWith(...otherSources: [...ObservableInputTuple]): OperatorFunction; @@ -144,7 +144,7 @@ export interface GroupByOptionsWithElement { element: (value: T) => E; } -export declare function ignoreElements(): OperatorFunction; +export declare function ignoreElements(): OperatorFunction; export declare function isEmpty(): OperatorFunction; @@ -157,7 +157,7 @@ export declare function last(predicate: (value: T, index: number, sour export declare function map(project: (value: T, index: number) => R): OperatorFunction; export declare function map(project: (this: A, value: T, index: number) => R, thisArg: A): OperatorFunction; -export declare function mapTo(value: R): OperatorFunction; +export declare function mapTo(value: R): OperatorFunction; export declare function mapTo(value: R): OperatorFunction; export declare function materialize(): OperatorFunction & ObservableNotification>; @@ -175,7 +175,7 @@ export declare function mergeMap>(project: (va export declare function mergeMap>(project: (value: T, index: number) => O, resultSelector: undefined, concurrent?: number): OperatorFunction>; export declare function mergeMap>(project: (value: T, index: number) => O, resultSelector: (outerValue: T, innerValue: ObservedValueOf, outerIndex: number, innerIndex: number) => R, concurrent?: number): OperatorFunction; -export declare function mergeMapTo>(innerObservable: O, concurrent?: number): OperatorFunction>; +export declare function mergeMapTo>(innerObservable: O, concurrent?: number): OperatorFunction>; export declare function mergeMapTo>(innerObservable: O, resultSelector: (outerValue: T, innerValue: ObservedValueOf, outerIndex: number, innerIndex: number) => R, concurrent?: number): OperatorFunction; export declare function mergeScan(accumulator: (acc: R, value: T, index: number) => ObservableInput, seed: R, concurrent?: number): OperatorFunction; @@ -300,8 +300,8 @@ export declare function switchMap>(project: (v export declare function switchMap>(project: (value: T, index: number) => O, resultSelector: undefined): OperatorFunction>; export declare function switchMap>(project: (value: T, index: number) => O, resultSelector: (outerValue: T, innerValue: ObservedValueOf, outerIndex: number, innerIndex: number) => R): OperatorFunction; -export declare function switchMapTo>(observable: O): OperatorFunction>; -export declare function switchMapTo>(observable: O, resultSelector: undefined): OperatorFunction>; +export declare function switchMapTo>(observable: O): OperatorFunction>; +export declare function switchMapTo>(observable: O, resultSelector: undefined): OperatorFunction>; export declare function switchMapTo>(observable: O, resultSelector: (outerValue: T, innerValue: ObservedValueOf, outerIndex: number, innerIndex: number) => R): OperatorFunction; export declare function switchScan>(accumulator: (acc: R, value: T, index: number) => O, seed: R): OperatorFunction>; diff --git a/docs_app/assets/Rx_Logo_S.png b/docs_app/assets/Rx_Logo_S.png deleted file mode 100644 index 752fac1e2d..0000000000 Binary files a/docs_app/assets/Rx_Logo_S.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/audit.png b/docs_app/assets/images/marble-diagrams/audit.png deleted file mode 100644 index ceca809ff0..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/audit.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/audit.svg b/docs_app/assets/images/marble-diagrams/audit.svg deleted file mode 100644 index 2c510189d6..0000000000 --- a/docs_app/assets/images/marble-diagrams/audit.svg +++ /dev/null @@ -1 +0,0 @@ -zyxcxbyxaiiiaudit()zxy \ No newline at end of file diff --git a/docs_app/assets/images/marble-diagrams/auditTime.png b/docs_app/assets/images/marble-diagrams/auditTime.png deleted file mode 100644 index a259f2bcc9..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/auditTime.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/buffer.png b/docs_app/assets/images/marble-diagrams/buffer.png deleted file mode 100644 index ccc9c33e35..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/buffer.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/bufferCount.png b/docs_app/assets/images/marble-diagrams/bufferCount.png deleted file mode 100644 index 36afdf75b7..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/bufferCount.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/bufferTime.png b/docs_app/assets/images/marble-diagrams/bufferTime.png deleted file mode 100644 index ae8c9dfc22..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/bufferTime.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/bufferToggle.png b/docs_app/assets/images/marble-diagrams/bufferToggle.png deleted file mode 100644 index 7257358745..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/bufferToggle.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/bufferWhen.png b/docs_app/assets/images/marble-diagrams/bufferWhen.png deleted file mode 100644 index 6165954d4d..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/bufferWhen.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/catch.png b/docs_app/assets/images/marble-diagrams/catch.png deleted file mode 100644 index f47e4f8e10..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/catch.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/combineAll.png b/docs_app/assets/images/marble-diagrams/combineAll.png deleted file mode 100644 index d9d240f183..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/combineAll.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/combineLatest.png b/docs_app/assets/images/marble-diagrams/combineLatest.png deleted file mode 100644 index 528041fd86..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/combineLatest.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/concat.png b/docs_app/assets/images/marble-diagrams/concat.png deleted file mode 100644 index dce8453f04..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/concat.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/concatAll.png b/docs_app/assets/images/marble-diagrams/concatAll.png deleted file mode 100644 index 687cdfa728..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/concatAll.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/concatAll.svg b/docs_app/assets/images/marble-diagrams/concatAll.svg deleted file mode 100755 index f7a5258ab7..0000000000 --- a/docs_app/assets/images/marble-diagrams/concatAll.svg +++ /dev/null @@ -1 +0,0 @@ -fedcbaconcatAllfedcba \ No newline at end of file diff --git a/docs_app/assets/images/marble-diagrams/concatMap.png b/docs_app/assets/images/marble-diagrams/concatMap.png deleted file mode 100644 index 38dfa20821..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/concatMap.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/concatMapTo.png b/docs_app/assets/images/marble-diagrams/concatMapTo.png deleted file mode 100644 index 10f60435e3..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/concatMapTo.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/count.png b/docs_app/assets/images/marble-diagrams/count.png deleted file mode 100644 index 0cf88b2ebd..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/count.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/debounce.png b/docs_app/assets/images/marble-diagrams/debounce.png deleted file mode 100644 index 91ed9bb1cf..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/debounce.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/debounce.svg b/docs_app/assets/images/marble-diagrams/debounce.svg deleted file mode 100644 index 689f7ef820..0000000000 --- a/docs_app/assets/images/marble-diagrams/debounce.svg +++ /dev/null @@ -1 +0,0 @@ -fedcbaxxxdebounce()fca \ No newline at end of file diff --git a/docs_app/assets/images/marble-diagrams/debounceTime.png b/docs_app/assets/images/marble-diagrams/debounceTime.png deleted file mode 100644 index c3e9efa633..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/debounceTime.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/defaultIfEmpty.png b/docs_app/assets/images/marble-diagrams/defaultIfEmpty.png deleted file mode 100644 index c76ccce12f..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/defaultIfEmpty.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/defer.png b/docs_app/assets/images/marble-diagrams/defer.png deleted file mode 100644 index 3eea61346d..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/defer.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/delay.png b/docs_app/assets/images/marble-diagrams/delay.png deleted file mode 100644 index 4f296f32c0..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/delay.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/delayWhen.png b/docs_app/assets/images/marble-diagrams/delayWhen.png deleted file mode 100644 index c766728d64..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/delayWhen.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/dematerialize.png b/docs_app/assets/images/marble-diagrams/dematerialize.png deleted file mode 100644 index 0799abeb52..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/dematerialize.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/elementAt.png b/docs_app/assets/images/marble-diagrams/elementAt.png deleted file mode 100644 index 3cd67518a6..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/elementAt.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/empty.png b/docs_app/assets/images/marble-diagrams/empty.png deleted file mode 100644 index e2928ddb59..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/empty.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/endWith.png b/docs_app/assets/images/marble-diagrams/endWith.png deleted file mode 100644 index 54c983eb47..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/endWith.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/every.png b/docs_app/assets/images/marble-diagrams/every.png deleted file mode 100644 index 63bcebc60c..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/every.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/exhaust.png b/docs_app/assets/images/marble-diagrams/exhaust.png deleted file mode 100644 index bd193bc950..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/exhaust.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/exhaustMap.png b/docs_app/assets/images/marble-diagrams/exhaustMap.png deleted file mode 100644 index df128b4d1c..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/exhaustMap.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/expand.png b/docs_app/assets/images/marble-diagrams/expand.png deleted file mode 100644 index 0f97e282f5..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/expand.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/filter.png b/docs_app/assets/images/marble-diagrams/filter.png deleted file mode 100644 index 7dabb61267..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/filter.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/find.png b/docs_app/assets/images/marble-diagrams/find.png deleted file mode 100644 index 343b826190..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/find.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/findIndex.png b/docs_app/assets/images/marble-diagrams/findIndex.png deleted file mode 100644 index abf1d2a029..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/findIndex.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/first.png b/docs_app/assets/images/marble-diagrams/first.png deleted file mode 100644 index 0fc0625b25..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/first.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/forkJoin.png b/docs_app/assets/images/marble-diagrams/forkJoin.png deleted file mode 100644 index 913993717d..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/forkJoin.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/from.png b/docs_app/assets/images/marble-diagrams/from.png deleted file mode 100644 index ab7d00cd78..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/from.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/fromEvent.png b/docs_app/assets/images/marble-diagrams/fromEvent.png deleted file mode 100644 index 452280f9ef..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/fromEvent.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/fromEventPattern.png b/docs_app/assets/images/marble-diagrams/fromEventPattern.png deleted file mode 100644 index 3e9d4d77d2..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/fromEventPattern.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/generate.png b/docs_app/assets/images/marble-diagrams/generate.png deleted file mode 100644 index 10b9a34a19..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/generate.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/groupBy.png b/docs_app/assets/images/marble-diagrams/groupBy.png deleted file mode 100644 index 29b80110df..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/groupBy.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/ignoreElements.png b/docs_app/assets/images/marble-diagrams/ignoreElements.png deleted file mode 100644 index 6dcb3a21b4..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/ignoreElements.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/interval.png b/docs_app/assets/images/marble-diagrams/interval.png deleted file mode 100644 index e7bbe99b5f..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/interval.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/isEmpty.png b/docs_app/assets/images/marble-diagrams/isEmpty.png deleted file mode 100644 index e3154db7f7..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/isEmpty.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/last.png b/docs_app/assets/images/marble-diagrams/last.png deleted file mode 100644 index e2078e3262..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/last.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/map.png b/docs_app/assets/images/marble-diagrams/map.png deleted file mode 100644 index c08038065e..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/map.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/mapTo.png b/docs_app/assets/images/marble-diagrams/mapTo.png deleted file mode 100644 index 4f47644cf1..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/mapTo.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/materialize.png b/docs_app/assets/images/marble-diagrams/materialize.png deleted file mode 100644 index c8a71319a9..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/materialize.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/max.png b/docs_app/assets/images/marble-diagrams/max.png deleted file mode 100644 index 017f6c7200..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/max.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/merge.png b/docs_app/assets/images/marble-diagrams/merge.png deleted file mode 100644 index 4785ecb253..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/merge.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/mergeAll.png b/docs_app/assets/images/marble-diagrams/mergeAll.png deleted file mode 100644 index 12c4be9ea3..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/mergeAll.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/mergeMap.png b/docs_app/assets/images/marble-diagrams/mergeMap.png deleted file mode 100644 index 730b5f07db..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/mergeMap.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/mergeMapTo.png b/docs_app/assets/images/marble-diagrams/mergeMapTo.png deleted file mode 100644 index 5fbac90eac..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/mergeMapTo.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/min.png b/docs_app/assets/images/marble-diagrams/min.png deleted file mode 100644 index 53a4d05b87..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/min.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/multicast.png b/docs_app/assets/images/marble-diagrams/multicast.png deleted file mode 100644 index 9b8fce695f..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/multicast.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/never.png b/docs_app/assets/images/marble-diagrams/never.png deleted file mode 100644 index 96300cab53..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/never.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/of.png b/docs_app/assets/images/marble-diagrams/of.png deleted file mode 100644 index 2013dcaf7d..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/of.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/onErrorResumeNext.png b/docs_app/assets/images/marble-diagrams/onErrorResumeNext.png deleted file mode 100644 index 878fac849d..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/onErrorResumeNext.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/pairs.png b/docs_app/assets/images/marble-diagrams/pairs.png deleted file mode 100644 index 4a514e0cd3..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/pairs.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/pairwise.png b/docs_app/assets/images/marble-diagrams/pairwise.png deleted file mode 100644 index 4d32f71998..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/pairwise.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/partition.png b/docs_app/assets/images/marble-diagrams/partition.png deleted file mode 100644 index ffd3b6b525..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/partition.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/pluck.png b/docs_app/assets/images/marble-diagrams/pluck.png deleted file mode 100644 index 9ddfcbe5ea..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/pluck.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/publish.png b/docs_app/assets/images/marble-diagrams/publish.png deleted file mode 100644 index 0834f221bb..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/publish.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/publishLast.png b/docs_app/assets/images/marble-diagrams/publishLast.png deleted file mode 100644 index 854cd36c3d..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/publishLast.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/race.png b/docs_app/assets/images/marble-diagrams/race.png deleted file mode 100644 index 84dcf0c90a..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/race.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/range.png b/docs_app/assets/images/marble-diagrams/range.png deleted file mode 100644 index 17dbd736c3..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/range.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/reduce.png b/docs_app/assets/images/marble-diagrams/reduce.png deleted file mode 100644 index 3988fafdd2..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/reduce.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/refCount.png b/docs_app/assets/images/marble-diagrams/refCount.png deleted file mode 100644 index 57b0328a10..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/refCount.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/repeat.png b/docs_app/assets/images/marble-diagrams/repeat.png deleted file mode 100644 index 9ef4598b7d..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/repeat.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/repeatWhen.png b/docs_app/assets/images/marble-diagrams/repeatWhen.png deleted file mode 100644 index 33f84a3ba6..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/repeatWhen.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/retry.png b/docs_app/assets/images/marble-diagrams/retry.png deleted file mode 100644 index 7a44168b27..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/retry.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/retryWhen.png b/docs_app/assets/images/marble-diagrams/retryWhen.png deleted file mode 100644 index a886f19f84..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/retryWhen.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/sample.png b/docs_app/assets/images/marble-diagrams/sample.png deleted file mode 100644 index f5da6f0801..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/sample.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/sampleTime.png b/docs_app/assets/images/marble-diagrams/sampleTime.png deleted file mode 100644 index f6e7f62466..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/sampleTime.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/scan.png b/docs_app/assets/images/marble-diagrams/scan.png deleted file mode 100644 index dd361b38f7..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/scan.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/sequenceEqual.png b/docs_app/assets/images/marble-diagrams/sequenceEqual.png deleted file mode 100644 index f0b648de19..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/sequenceEqual.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/share.png b/docs_app/assets/images/marble-diagrams/share.png deleted file mode 100644 index a73805d8d3..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/share.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/single.png b/docs_app/assets/images/marble-diagrams/single.png deleted file mode 100644 index f6a28d2e9c..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/single.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/skip.png b/docs_app/assets/images/marble-diagrams/skip.png deleted file mode 100644 index 855b81d897..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/skip.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/skipLast.png b/docs_app/assets/images/marble-diagrams/skipLast.png deleted file mode 100644 index 8c98d68cd4..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/skipLast.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/skipUntil.png b/docs_app/assets/images/marble-diagrams/skipUntil.png deleted file mode 100644 index c782223d97..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/skipUntil.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/skipWhile.png b/docs_app/assets/images/marble-diagrams/skipWhile.png deleted file mode 100644 index e740672ec7..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/skipWhile.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/startWith.png b/docs_app/assets/images/marble-diagrams/startWith.png deleted file mode 100644 index de31f98bce..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/startWith.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/subscribeOn.png b/docs_app/assets/images/marble-diagrams/subscribeOn.png deleted file mode 100644 index 618e7a77f5..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/subscribeOn.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/switchAll.png b/docs_app/assets/images/marble-diagrams/switchAll.png deleted file mode 100644 index ed3223a173..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/switchAll.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/switchMap.png b/docs_app/assets/images/marble-diagrams/switchMap.png deleted file mode 100644 index 721b30bd9e..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/switchMap.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/switchMapTo.png b/docs_app/assets/images/marble-diagrams/switchMapTo.png deleted file mode 100644 index f255242789..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/switchMapTo.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/take.png b/docs_app/assets/images/marble-diagrams/take.png deleted file mode 100644 index 8ef188dcdf..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/take.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/takeLast.png b/docs_app/assets/images/marble-diagrams/takeLast.png deleted file mode 100644 index a92c41be75..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/takeLast.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/takeUntil.png b/docs_app/assets/images/marble-diagrams/takeUntil.png deleted file mode 100644 index eba960e63d..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/takeUntil.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/takeWhile.png b/docs_app/assets/images/marble-diagrams/takeWhile.png deleted file mode 100644 index 2e1e1830bf..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/takeWhile.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/tap.png b/docs_app/assets/images/marble-diagrams/tap.png deleted file mode 100644 index 1ea11d3d32..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/tap.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/throttle.png b/docs_app/assets/images/marble-diagrams/throttle.png deleted file mode 100644 index 18a69a0697..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/throttle.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/throttle.svg b/docs_app/assets/images/marble-diagrams/throttle.svg deleted file mode 100644 index ee250face1..0000000000 --- a/docs_app/assets/images/marble-diagrams/throttle.svg +++ /dev/null @@ -1 +0,0 @@ -zyxcxbyxaiiithrottle()cba \ No newline at end of file diff --git a/docs_app/assets/images/marble-diagrams/throttleTime.png b/docs_app/assets/images/marble-diagrams/throttleTime.png deleted file mode 100644 index 23954c5a06..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/throttleTime.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/throw.png b/docs_app/assets/images/marble-diagrams/throw.png deleted file mode 100644 index befdd36961..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/throw.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/throwIfEmpty.png b/docs_app/assets/images/marble-diagrams/throwIfEmpty.png deleted file mode 100644 index a463ec0af7..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/throwIfEmpty.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/timeinterval.png b/docs_app/assets/images/marble-diagrams/timeinterval.png deleted file mode 100644 index 4f24523525..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/timeinterval.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/timeout.png b/docs_app/assets/images/marble-diagrams/timeout.png deleted file mode 100644 index 8b1d99c483..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/timeout.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/timeoutWith.png b/docs_app/assets/images/marble-diagrams/timeoutWith.png deleted file mode 100644 index 1fee9b9341..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/timeoutWith.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/timer.png b/docs_app/assets/images/marble-diagrams/timer.png deleted file mode 100644 index 2299f1c285..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/timer.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/timestamp.png b/docs_app/assets/images/marble-diagrams/timestamp.png deleted file mode 100644 index f2895b4305..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/timestamp.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/toArray.png b/docs_app/assets/images/marble-diagrams/toArray.png deleted file mode 100644 index 0c8cb4e128..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/toArray.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/window.png b/docs_app/assets/images/marble-diagrams/window.png deleted file mode 100644 index 1fbe7c963d..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/window.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/windowCount.png b/docs_app/assets/images/marble-diagrams/windowCount.png deleted file mode 100644 index 6ebbaada90..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/windowCount.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/windowTime.png b/docs_app/assets/images/marble-diagrams/windowTime.png deleted file mode 100644 index 7c3adcb948..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/windowTime.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/windowToggle.png b/docs_app/assets/images/marble-diagrams/windowToggle.png deleted file mode 100644 index 4d8489513c..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/windowToggle.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/windowWhen.png b/docs_app/assets/images/marble-diagrams/windowWhen.png deleted file mode 100644 index 0d3f93812a..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/windowWhen.png and /dev/null differ diff --git a/docs_app/assets/images/marble-diagrams/withLatestFrom.png b/docs_app/assets/images/marble-diagrams/withLatestFrom.png deleted file mode 100644 index 499cacbaff..0000000000 Binary files a/docs_app/assets/images/marble-diagrams/withLatestFrom.png and /dev/null differ diff --git a/docs_app/content/deprecations/multicasting.md b/docs_app/content/deprecations/multicasting.md index 2d5ee9c900..2e77adc612 100644 --- a/docs_app/content/deprecations/multicasting.md +++ b/docs_app/content/deprecations/multicasting.md @@ -34,7 +34,8 @@ Instead of creating a [ConnectableObservable](/api/index/class/ConnectableObserv ```ts -import { ConnectableObservable, Subject, timer } from 'rxjs'; +import { ConnectableObservable, timer, Subject } from 'rxjs'; + // deprecated const tick$ = new ConnectableObservable( timer(1_000), @@ -44,7 +45,8 @@ tick$.connect(); ```ts -import { connectable, Subject, timer } from 'rxjs'; +import { connectable, timer, Subject } from 'rxjs'; + // suggested refactor const tick$ = connectable(timer(1_000), { connector: () => new Subject() @@ -56,7 +58,8 @@ In situations in which the `refCount` method is used, the [share](/api/operators ```ts -import { ConnectableObservable, Subject, timer } from 'rxjs'; +import { ConnectableObservable, timer, Subject } from 'rxjs'; + // deprecated const tick$ = new ConnectableObservable( timer(1_000), @@ -66,8 +69,8 @@ const tick$ = new ConnectableObservable( ```ts -import { Subject, timer } from 'rxjs'; -import { share } from 'rxjs/operators'; +import { timer, share, Subject } from 'rxjs'; + // suggested refactor const tick$ = timer(1_000).pipe( share({ connector: () => new Subject() }) @@ -80,8 +83,8 @@ Where [multicast](/api/operators/multicast) is called with a subject factory, ca ```ts -import { ConnectableObservable, timer, Subject } from 'rxjs'; -import { multicast } from 'rxjs/operators'; +import { timer, multicast, Subject, ConnectableObservable } from 'rxjs'; + // deprecated const tick$ = timer(1_000).pipe( multicast(() => new Subject()) @@ -91,6 +94,7 @@ const tick$ = timer(1_000).pipe( ```ts import { connectable, timer, Subject } from 'rxjs'; + // suggested refactor const tick$ = connectable(timer(1_000), { connector: () => new Subject() @@ -101,8 +105,8 @@ Where [multicast](/api/operators/multicast) is called with a subject instance, i ```ts -import { ConnectableObservable, timer, Subject } from 'rxjs'; -import { multicast } from 'rxjs/operators'; +import { timer, multicast, Subject, ConnectableObservable } from 'rxjs'; + // deprecated const tick$ = timer(1_000).pipe( multicast(new Subject()) @@ -112,6 +116,7 @@ const tick$ = timer(1_000).pipe( ```ts import { connectable, timer, Subject } from 'rxjs'; + // suggested refactor const tick$ = connectable(timer(1_000), { connector: () => new Subject(), @@ -123,8 +128,8 @@ Where [multicast](/api/operators/multicast) is used in conjunction with [refCoun ```ts -import { timer, Subject } from 'rxjs'; -import { multicast, refCount } from 'rxjs/operators'; +import { timer, multicast, Subject, refCount } from 'rxjs'; + // deprecated const tick$ = timer(1_000).pipe( multicast(() => new Subject()), @@ -134,8 +139,8 @@ const tick$ = timer(1_000).pipe( ```ts -import { timer, Subject } from 'rxjs'; -import { share } from 'rxjs/operators'; +import { timer, share, Subject } from 'rxjs'; + // suggested refactor const tick$ = timer(1_000).pipe( share({ connector: () => new Subject() }) @@ -146,8 +151,8 @@ Where [multicast](/api/operators/multicast) is used with a selector, it can be r ```ts -import { timer, combineLatest } from 'rxjs'; -import { multicast } from 'rxjs/operators'; +import { timer, multicast, Subject, combineLatest } from 'rxjs'; + // deprecated const tick$ = timer(1_000).pipe( multicast( @@ -159,8 +164,8 @@ const tick$ = timer(1_000).pipe( ```ts -import { timer, combineLatest } from 'rxjs'; -import { connect } from 'rxjs/operators'; +import { timer, connect, combineLatest, Subject } from 'rxjs'; + // suggested refactor const tick$ = timer(1_000).pipe( connect((source) => combineLatest([source, source]), { @@ -175,8 +180,8 @@ If you're using [publish](/api/operators/publish) to create a [ConnectableObserv ```ts -import { ConnectableObservable, timer } from 'rxjs'; -import { publish } from 'rxjs/operators'; +import { timer, publish, ConnectableObservable } from 'rxjs'; + // deprecated const tick$ = timer(1_000).pipe( publish() @@ -185,7 +190,8 @@ const tick$ = timer(1_000).pipe( ```ts -import { connectable, timer } from 'rxjs'; +import { connectable, timer, Subject } from 'rxjs'; + // suggested refactor const tick$ = connectable(timer(1_000), { connector: () => new Subject(), @@ -197,8 +203,8 @@ And if [refCount](/api/operators/refCount) is being applied to the result of [pu ```ts -import { timer } from 'rxjs'; -import { publish, refCount } from 'rxjs/operators'; +import { timer, publish, refCount } from 'rxjs'; + // deprecated const tick$ = timer(1_000).pipe( publish(), @@ -208,14 +214,14 @@ const tick$ = timer(1_000).pipe( ```ts -import { timer } from 'rxjs'; -import { share } from 'rxjs/operators'; +import { timer, share } from 'rxjs'; + // suggested refactor const tick$ = timer(1_000).pipe( share({ resetOnError: false, resetOnComplete: false, - resetOnRefCountZero: false, + resetOnRefCountZero: false }) ); ``` @@ -224,8 +230,8 @@ If [publish](/api/operators/publish) is being called with a selector, you can us ```ts -import { timer, combineLatest } from 'rxjs'; -import { publish } from 'rxjs/operators'; +import { timer, publish, combineLatest } from 'rxjs'; + // deprecated const tick$ = timer(1_000).pipe( publish((source) => combineLatest([source, source])) @@ -234,8 +240,8 @@ const tick$ = timer(1_000).pipe( ```ts -import { timer, combineLatest } from 'rxjs'; -import { connect } from 'rxjs/operators'; +import { timer, connect, combineLatest } from 'rxjs'; + // suggested refactor const tick$ = timer(1_000).pipe( connect((source) => combineLatest([source, source])) @@ -248,8 +254,8 @@ If you're using [publishBehavior](/api/operators/publishBehavior) to create a [C ```ts -import { ConnectableObservable, timer } from 'rxjs'; -import { publishBehavior } from 'rxjs/operators'; +import { timer, publishBehavior, ConnectableObservable } from 'rxjs'; + // deprecated const tick$ = timer(1_000).pipe( publishBehavior(0) @@ -259,6 +265,7 @@ const tick$ = timer(1_000).pipe( ```ts import { connectable, timer, BehaviorSubject } from 'rxjs'; + // suggested refactor const tick$ = connectable(timer(1_000), { connector: () => new BehaviorSubject(0), @@ -270,8 +277,8 @@ And if [refCount](/api/operators/refCount) is being applied to the result of [pu ```ts -import { timer } from 'rxjs'; -import { publishBehavior, refCount } from 'rxjs/operators'; +import { timer, publishBehavior, refCount } from 'rxjs'; + // deprecated const tick$ = timer(1_000).pipe( publishBehavior(0), @@ -281,15 +288,15 @@ const tick$ = timer(1_000).pipe( ```ts -import { timer, BehaviorSubject } from 'rxjs'; -import { share } from 'rxjs/operators'; +import { timer, share, BehaviorSubject } from 'rxjs'; + // suggested refactor const tick$ = timer(1_000).pipe( share({ connector: () => new BehaviorSubject(0), resetOnError: false, resetOnComplete: false, - resetOnRefCountZero: false, + resetOnRefCountZero: false }) ); ``` @@ -300,8 +307,8 @@ If you're using [publishLast](/api/operators/publishLast) to create a [Connectab ```ts -import { ConnectableObservable, timer } from 'rxjs'; -import { publishLast } from 'rxjs/operators'; +import { timer, publishLast, ConnectableObservable } from 'rxjs'; + // deprecated const tick$ = timer(1_000).pipe( publishLast() @@ -311,6 +318,7 @@ const tick$ = timer(1_000).pipe( ```ts import { connectable, timer, AsyncSubject } from 'rxjs'; + // suggested refactor const tick$ = connectable(timer(1_000), { connector: () => new AsyncSubject(), @@ -322,8 +330,8 @@ And if [refCount](/api/operators/refCount) is being applied to the result of [pu ```ts -import { timer } from 'rxjs'; -import { publishLast, refCount } from 'rxjs/operators'; +import { timer, publishLast, refCount } from 'rxjs'; + // deprecated const tick$ = timer(1_000).pipe( publishLast(), @@ -333,15 +341,15 @@ const tick$ = timer(1_000).pipe( ```ts -import { timer, AsyncSubject } from 'rxjs'; -import { share } from 'rxjs/operators'; +import { timer, share, AsyncSubject } from 'rxjs'; + // suggested refactor const tick$ = timer(1_000).pipe( share({ connector: () => new AsyncSubject(), resetOnError: false, resetOnComplete: false, - resetOnRefCountZero: false, + resetOnRefCountZero: false }) ); ``` @@ -352,8 +360,8 @@ If you're using [publishReplay](/api/operators/publishReplay) to create a [Conne ```ts -import { ConnectableObservable, timer } from 'rxjs'; -import { publishReplay } from 'rxjs/operators'; +import { timer, publishReplay, ConnectableObservable } from 'rxjs'; + // deprecated const tick$ = timer(1_000).pipe( publishReplay(1) @@ -363,6 +371,7 @@ const tick$ = timer(1_000).pipe( ```ts import { connectable, timer, ReplaySubject } from 'rxjs'; + // suggested refactor const tick$ = connectable(timer(1_000), { connector: () => new ReplaySubject(1), @@ -374,8 +383,8 @@ And if [refCount](/api/operators/refCount) is being applied to the result of [pu ```ts -import { timer } from 'rxjs'; -import { publishReplay, refCount } from 'rxjs/operators'; +import { timer, publishReplay, refCount } from 'rxjs'; + // deprecated const tick$ = timer(1_000).pipe( publishReplay(1), @@ -385,15 +394,15 @@ const tick$ = timer(1_000).pipe( ```ts -import { timer, ReplaySubject } from 'rxjs'; -import { share } from 'rxjs/operators'; +import { timer, share, ReplaySubject } from 'rxjs'; + // suggested refactor const tick$ = timer(1_000).pipe( share({ connector: () => new ReplaySubject(1), resetOnError: false, resetOnComplete: false, - resetOnRefCountZero: false, + resetOnRefCountZero: false }) ); ``` @@ -402,8 +411,8 @@ If [publishReplay](/api/operators/publishReplay) is being called with a selector ```ts -import { timer, combineLatest } from 'rxjs'; -import { publishReplay } from 'rxjs/operators'; +import { timer, publishReplay, combineLatest } from 'rxjs'; + // deprecated const tick$ = timer(1_000).pipe( publishReplay(1, undefined, (source) => combineLatest([source, source])) @@ -412,8 +421,8 @@ const tick$ = timer(1_000).pipe( ```ts -import { timer, combineLatest, ReplaySubject } from 'rxjs'; -import { connect } from 'rxjs/operators'; +import { timer, connect, combineLatest, ReplaySubject } from 'rxjs'; + // suggested refactor const tick$ = timer(1_000).pipe( connect((source) => combineLatest([source, source]), { diff --git a/docs_app/content/deprecations/resultSelector.md b/docs_app/content/deprecations/resultSelector.md index 4fe676ff79..9f28940bdd 100644 --- a/docs_app/content/deprecations/resultSelector.md +++ b/docs_app/content/deprecations/resultSelector.md @@ -28,24 +28,16 @@ There were two reasons for actually deprecating those parameters: Instead of using the `resultSelector` Argument, you can leverage the [`map`](/api/operators/map) operator on the inner Observable: + ```ts - -import {fromEvent, interval} from 'rxjs'; -import {switchMap, map} from 'rxjs/operators'; +import { fromEvent, switchMap, interval, map } from 'rxjs'; // deprecated fromEvent(document, 'click').pipe( - switchMap(x => interval(0, 1000), (x) => x+1) + switchMap((x) => interval(1000), (_, x) => x + 1) ); // suggested change fromEvent(document, 'click').pipe( - switchMap(x => interval(0, 1000).pipe( - map(x => x+1) - )) + switchMap((x) => interval(1000).pipe(map((x) => x + 1))) ); ``` - - - - - diff --git a/docs_app/content/deprecations/scheduler-argument.md b/docs_app/content/deprecations/scheduler-argument.md index d9d80e6597..5ce868b543 100644 --- a/docs_app/content/deprecations/scheduler-argument.md +++ b/docs_app/content/deprecations/scheduler-argument.md @@ -55,8 +55,7 @@ concat(of('hello '), of('World'), asyncScheduler).subscribe((x) => console.log(x To work around this deprecation you can leverage the [`scheduled`](/api/index/function/scheduled) function. ```ts -import { scheduled, of, asyncScheduler } from 'rxjs'; -import { concatAll } from 'rxjs/operators'; +import { scheduled, of, asyncScheduler, concatAll } from 'rxjs'; scheduled([of('hello '), of('World')], asyncScheduler) .pipe(concatAll()) @@ -78,8 +77,7 @@ combineLatest(of('hello '), of('World'), asyncScheduler).subscribe(console.log); would become: ```ts -import { scheduled, of, asyncScheduler } from 'rxjs'; -import { combineLatestAll } from 'rxjs/operators'; +import { scheduled, of, asyncScheduler, combineLatestAll } from 'rxjs'; scheduled([of('hello '), of('World')], asyncScheduler) .pipe(combineLatestAll()) diff --git a/docs_app/content/deprecations/to-promise.md b/docs_app/content/deprecations/to-promise.md index 40a616b2c4..40fce4a0bc 100644 --- a/docs_app/content/deprecations/to-promise.md +++ b/docs_app/content/deprecations/to-promise.md @@ -31,8 +31,7 @@ the return type change), while the `lastValueFrom` will reject with the {@link E ### Example ```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)); diff --git a/docs_app/content/guide/operators.md b/docs_app/content/guide/operators.md index 01f779bea2..171a7d6168 100644 --- a/docs_app/content/guide/operators.md +++ b/docs_app/content/guide/operators.md @@ -17,8 +17,7 @@ A Pipeable Operator is essentially a pure function which takes one Observable as For example, the operator called [`map`](/api/operators/map) is analogous to the Array method of the same name. Just as `[1, 2, 3].map(x => x * x)` will yield `[1, 4, 9]`, the Observable created like this: ```ts -import { of } from 'rxjs'; -import { map } from 'rxjs/operators'; +import { of, map } from 'rxjs'; of(1, 2, 3) .pipe(map((x) => x * x)) @@ -33,8 +32,7 @@ of(1, 2, 3) will emit `1`, `4`, `9`. Another useful operator is [`first`](/api/operators/first): ```ts -import { of } from 'rxjs'; -import { first } from 'rxjs/operators'; +import { of, first } from 'rxjs'; of(1, 2, 3) .pipe(first()) @@ -270,8 +268,7 @@ If there is a commonly used sequence of operators in your code, use the `pipe()` For example, you could make a function that discarded odd values and doubled even values like this: ```ts -import { pipe } from 'rxjs'; -import { filter, map } from 'rxjs/operators'; +import { pipe, filter, map } from 'rxjs'; function discardOddDoubleEven() { return pipe( diff --git a/docs_app/content/guide/overview.md b/docs_app/content/guide/overview.md index 0f43f2813b..23dc95a2cf 100644 --- a/docs_app/content/guide/overview.md +++ b/docs_app/content/guide/overview.md @@ -46,12 +46,11 @@ document.addEventListener('click', () => console.log(`Clicked ${++count} times`) Using RxJS you isolate the state. ```ts -import { fromEvent } from 'rxjs'; -import { scan } from 'rxjs/operators'; +import { fromEvent, scan } from 'rxjs'; fromEvent(document, 'click') - .pipe(scan(count => count + 1, 0)) - .subscribe(count => console.log(`Clicked ${count} times`)); + .pipe(scan((count) => count + 1, 0)) + .subscribe((count) => console.log(`Clicked ${count} times`)); ``` The **scan** operator works just like **reduce** for arrays. It takes a value which is exposed to a callback. The returned value of the callback will then become the next value exposed the next time the callback runs. @@ -77,15 +76,14 @@ document.addEventListener('click', () => { With RxJS: ```ts -import { fromEvent } from 'rxjs'; -import { throttleTime, scan } from 'rxjs/operators'; +import { fromEvent, throttleTime, scan } from 'rxjs'; fromEvent(document, 'click') .pipe( throttleTime(1000), - scan(count => count + 1, 0) + scan((count) => count + 1, 0) ) - .subscribe(count => console.log(`Clicked ${count} times`)); + .subscribe((count) => console.log(`Clicked ${count} times`)); ``` Other flow control operators are [**filter**](../api/operators/filter), [**delay**](../api/operators/delay), [**debounceTime**](../api/operators/debounceTime), [**take**](../api/operators/take), [**takeUntil**](../api/operators/takeUntil), [**distinct**](../api/operators/distinct), [**distinctUntilChanged**](../api/operators/distinctUntilChanged) etc. @@ -100,7 +98,7 @@ Here's how you can add the current mouse x position for every click, in plain Ja let count = 0; const rate = 1000; let lastClick = Date.now() - rate; -document.addEventListener('click', event => { +document.addEventListener('click', (event) => { if (Date.now() - lastClick >= rate) { count += event.clientX; console.log(count); @@ -112,16 +110,15 @@ document.addEventListener('click', event => { With RxJS: ```ts -import { fromEvent } from 'rxjs'; -import { throttleTime, map, scan } from 'rxjs/operators'; +import { fromEvent, throttleTime, map, scan } from 'rxjs'; fromEvent(document, 'click') .pipe( throttleTime(1000), - map(event => event.clientX), + map((event) => event.clientX), scan((count, clientX) => count + clientX, 0) ) - .subscribe(count => console.log(count)); + .subscribe((count) => console.log(count)); ``` Other value producing operators are [**pluck**](../api/operators/pluck), [**pairwise**](../api/operators/pairwise), [**sample**](../api/operators/sample) etc. diff --git a/docs_app/content/guide/scheduler.md b/docs_app/content/guide/scheduler.md index 3aa88c4e7a..38de9d45d4 100644 --- a/docs_app/content/guide/scheduler.md +++ b/docs_app/content/guide/scheduler.md @@ -10,9 +10,9 @@ In the example below, we take the usual simple Observable that emits values `1`, `2`, `3` synchronously, and use the operator `observeOn` to specify the `async` scheduler to use for delivering those values. + ```ts -import { Observable, asyncScheduler } from 'rxjs'; -import { observeOn } from 'rxjs/operators'; +import { Observable, observeOn, asyncScheduler } from 'rxjs'; const observable = new Observable((observer) => { observer.next(1); @@ -26,14 +26,14 @@ const observable = new Observable((observer) => { console.log('just before subscribe'); observable.subscribe({ next(x) { - console.log('got value ' + x) + console.log('got value ' + x); }, error(err) { console.error('something wrong occurred: ' + err); }, complete() { - console.log('done'); - } + console.log('done'); + }, }); console.log('just after subscribe'); ``` @@ -51,11 +51,11 @@ done Notice how the notifications `got value...` were delivered after `just after subscribe`, which is different to the default behavior we have seen so far. This is because `observeOn(asyncScheduler)` introduces a proxy Observer between `new Observable` and the final Observer. Let's rename some identifiers to make that distinction obvious in the example code: + ```ts -import { Observable, asyncScheduler } from 'rxjs'; -import { observeOn } from 'rxjs/operators'; +import { Observable, observeOn, asyncScheduler } from 'rxjs'; -var observable = new Observable((proxyObserver) => { +const observable = new Observable((proxyObserver) => { proxyObserver.next(1); proxyObserver.next(2); proxyObserver.next(3); @@ -64,16 +64,16 @@ var observable = new Observable((proxyObserver) => { observeOn(asyncScheduler) ); -var finalObserver = { +const finalObserver = { next(x) { - console.log('got value ' + x) + console.log('got value ' + x); }, error(err) { console.error('something wrong occurred: ' + err); }, complete() { - console.log('done'); - } + console.log('done'); + }, }; console.log('just before subscribe'); @@ -83,6 +83,7 @@ console.log('just after subscribe'); The `proxyObserver` is created in `observeOn(asyncScheduler)`, and its `next(val)` function is approximately the following: + ```ts const proxyObserver = { next(val) { @@ -94,31 +95,30 @@ const proxyObserver = { }, // ... -} +}; ``` The `async` Scheduler operates with a `setTimeout` or `setInterval`, even if the given `delay` was zero. As usual, in JavaScript, `setTimeout(fn, 0)` is known to run the function `fn` earliest on the next event loop iteration. This explains why `got value 1` is delivered to the `finalObserver` after `just after subscribe` happened. -The `schedule()` method of a Scheduler takes a `delay` argument, which refers to a quantity of time relative to the Scheduler's own internal clock. A Scheduler's clock need not have any relation to the actual wall-clock time. This is how temporal operators like `delay` operate not on actual time, but on time dictated by the Scheduler's clock. This is specially useful in testing, where a *virtual time Scheduler* may be used to fake wall-clock time while in reality executing scheduled tasks synchronously. +The `schedule()` method of a Scheduler takes a `delay` argument, which refers to a quantity of time relative to the Scheduler's own internal clock. A Scheduler's clock need not have any relation to the actual wall-clock time. This is how temporal operators like `delay` operate not on actual time, but on time dictated by the Scheduler's clock. This is specially useful in testing, where a _virtual time Scheduler_ may be used to fake wall-clock time while in reality executing scheduled tasks synchronously. ## Scheduler Types The `async` Scheduler is one of the built-in schedulers provided by RxJS. Each of these can be created and returned by using static properties of the `Scheduler` object. -| Scheduler | Purpose | -| --- | --- | -| `null` | By not passing any scheduler, notifications are delivered synchronously and recursively. Use this for constant-time operations or tail recursive operations. | -| `queueScheduler` | Schedules on a queue in the current event frame (trampoline scheduler). Use this for iteration operations. | -| `asapScheduler` | Schedules on the micro task queue, which is the same queue used for promises. Basically after the current job, but before the next job. Use this for asynchronous conversions. | -| `asyncScheduler` | Schedules work with `setInterval`. Use this for time-based operations. | -| `animationFrameScheduler` | Schedules task that will happen just before next browser content repaint. Can be used to create smooth browser animations.| - +| Scheduler | Purpose | +| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `null` | By not passing any scheduler, notifications are delivered synchronously and recursively. Use this for constant-time operations or tail recursive operations. | +| `queueScheduler` | Schedules on a queue in the current event frame (trampoline scheduler). Use this for iteration operations. | +| `asapScheduler` | Schedules on the micro task queue, which is the same queue used for promises. Basically after the current job, but before the next job. Use this for asynchronous conversions. | +| `asyncScheduler` | Schedules work with `setInterval`. Use this for time-based operations. | +| `animationFrameScheduler` | Schedules task that will happen just before next browser content repaint. Can be used to create smooth browser animations. | ## Using Schedulers -You may have already used schedulers in your RxJS code without explicitly stating the type of schedulers to be used. This is because all Observable operators that deal with concurrency have optional schedulers. If you do not provide the scheduler, RxJS will pick a default scheduler by using the principle of least concurrency. This means that the scheduler which introduces the least amount of concurrency that satisfies the needs of the operator is chosen. For example, for operators returning an observable with a finite and small number of messages, RxJS uses no Scheduler, i.e. `null` or `undefined`. For operators returning a potentially large or infinite number of messages, `queue` Scheduler is used. For operators which use timers, `async` is used. +You may have already used schedulers in your RxJS code without explicitly stating the type of schedulers to be used. This is because all Observable operators that deal with concurrency have optional schedulers. If you do not provide the scheduler, RxJS will pick a default scheduler by using the principle of least concurrency. This means that the scheduler which introduces the least amount of concurrency that satisfies the needs of the operator is chosen. For example, for operators returning an observable with a finite and small number of messages, RxJS uses no Scheduler, i.e. `null` or `undefined`. For operators returning a potentially large or infinite number of messages, `queue` Scheduler is used. For operators which use timers, `async` is used. -Because RxJS uses the least concurrency scheduler, you can pick a different scheduler if you want to introduce concurrency for performance purpose. To specify a particular scheduler, you can use those operator methods that take a scheduler, e.g., `from([10, 20, 30], asyncScheduler)`. +Because RxJS uses the least concurrency scheduler, you can pick a different scheduler if you want to introduce concurrency for performance purpose. To specify a particular scheduler, you can use those operator methods that take a scheduler, e.g., `from([10, 20, 30], asyncScheduler)`. **Static creation operators usually take a Scheduler as argument.** For instance, `from(array, scheduler)` lets you specify the Scheduler to use when delivering each notification converted from the `array`. It is usually the last argument to the operator. The following static creation operators take a Scheduler argument: diff --git a/docs_app/content/guide/subject.md b/docs_app/content/guide/subject.md index 5c281f413f..2938b633d9 100644 --- a/docs_app/content/guide/subject.md +++ b/docs_app/content/guide/subject.md @@ -18,10 +18,10 @@ import { Subject } from 'rxjs'; const subject = new Subject(); subject.subscribe({ - next: (v) => console.log(`observerA: ${v}`) + next: (v) => console.log(`observerA: ${v}`), }); subject.subscribe({ - next: (v) => console.log(`observerB: ${v}`) + next: (v) => console.log(`observerB: ${v}`), }); subject.next(1); @@ -42,10 +42,10 @@ import { Subject, from } from 'rxjs'; const subject = new Subject(); subject.subscribe({ - next: (v) => console.log(`observerA: ${v}`) + next: (v) => console.log(`observerA: ${v}`), }); subject.subscribe({ - next: (v) => console.log(`observerB: ${v}`) + next: (v) => console.log(`observerB: ${v}`), }); const observable = from([1, 2, 3]); @@ -74,8 +74,7 @@ A "multicasted Observable" passes notifications through a Subject which may have Under the hood, this is how the `multicast` operator works: Observers subscribe to an underlying Subject, and the Subject subscribes to the source Observable. The following example is similar to the previous example which used `observable.subscribe(subject)`: ```ts -import { from, Subject } from 'rxjs'; -import { multicast } from 'rxjs/operators'; +import { from, Subject, multicast } from 'rxjs'; const source = from([1, 2, 3]); const subject = new Subject(); @@ -83,10 +82,10 @@ const multicasted = source.pipe(multicast(subject)); // These are, under the hood, `subject.subscribe({...})`: multicasted.subscribe({ - next: (v) => console.log(`observerA: ${v}`) + next: (v) => console.log(`observerA: ${v}`), }); multicasted.subscribe({ - next: (v) => console.log(`observerB: ${v}`) + next: (v) => console.log(`observerB: ${v}`), }); // This is, under the hood, `source.subscribe(subject)`: @@ -95,11 +94,11 @@ multicasted.connect(); `multicast` returns an Observable that looks like a normal Observable, but works like a Subject when it comes to subscribing. `multicast` returns a `ConnectableObservable`, which is simply an Observable with the `connect()` method. -The `connect()` method is important to determine exactly when the shared Observable execution will start. Because `connect()` does `source.subscribe(subject)` under the hood, `connect()` returns a Subscription, which you can unsubscribe from in order to cancel the shared Observable execution. +The `connect()` method is important to determine exactly when the shared Observable execution will start. Because `connect()` does `source.subscribe(subject)` under the hood, `connect()` returns a Subscription, which you can unsubscribe from in order to cancel the shared Observable execution. ### Reference counting -Calling `connect()` manually and handling the Subscription is often cumbersome. Usually, we want to *automatically* connect when the first Observer arrives, and automatically cancel the shared execution when the last Observer unsubscribes. +Calling `connect()` manually and handling the Subscription is often cumbersome. Usually, we want to _automatically_ connect when the first Observer arrives, and automatically cancel the shared execution when the last Observer unsubscribes. Consider the following example where subscriptions occur as outlined by this list: @@ -108,17 +107,16 @@ Consider the following example where subscriptions occur as outlined by this lis 3. The `next` value `0` is delivered to the first Observer 4. Second Observer subscribes to the multicasted Observable 5. The `next` value `1` is delivered to the first Observer -5. The `next` value `1` is delivered to the second Observer -1. First Observer unsubscribes from the multicasted Observable -5. The `next` value `2` is delivered to the second Observer -1. Second Observer unsubscribes from the multicasted Observable -1. **The connection to the multicasted Observable is unsubscribed** +6. The `next` value `1` is delivered to the second Observer +7. First Observer unsubscribes from the multicasted Observable +8. The `next` value `2` is delivered to the second Observer +9. Second Observer unsubscribes from the multicasted Observable +10. **The connection to the multicasted Observable is unsubscribed** To achieve that with explicit calls to `connect()`, we write the following code: ```ts -import { interval, Subject } from 'rxjs'; -import { multicast } from 'rxjs/operators'; +import { interval, Subject, multicast } from 'rxjs'; const source = interval(500); const subject = new Subject(); @@ -126,7 +124,7 @@ const multicasted = source.pipe(multicast(subject)); let subscription1, subscription2, subscriptionConnect; subscription1 = multicasted.subscribe({ - next: (v) => console.log(`observerA: ${v}`) + next: (v) => console.log(`observerA: ${v}`), }); // We should call `connect()` here, because the first // subscriber to `multicasted` is interested in consuming values @@ -134,7 +132,7 @@ subscriptionConnect = multicasted.connect(); setTimeout(() => { subscription2 = multicasted.subscribe({ - next: (v) => console.log(`observerB: ${v}`) + next: (v) => console.log(`observerB: ${v}`), }); }, 600); @@ -157,8 +155,7 @@ If we wish to avoid explicit calls to `connect()`, we can use ConnectableObserva Below is an example: ```ts -import { interval, Subject } from 'rxjs'; -import { multicast, refCount } from 'rxjs/operators'; +import { interval, Subject, multicast, refCount } from 'rxjs'; const source = interval(500); const subject = new Subject(); @@ -169,13 +166,13 @@ let subscription1, subscription2; // it is the first subscriber to `refCounted` console.log('observerA subscribed'); subscription1 = refCounted.subscribe({ - next: (v) => console.log(`observerA: ${v}`) + next: (v) => console.log(`observerA: ${v}`), }); setTimeout(() => { console.log('observerB subscribed'); subscription2 = refCounted.subscribe({ - next: (v) => console.log(`observerB: ${v}`) + next: (v) => console.log(`observerB: ${v}`), }); }, 600); @@ -217,14 +214,14 @@ import { BehaviorSubject } from 'rxjs'; const subject = new BehaviorSubject(0); // 0 is the initial value subject.subscribe({ - next: (v) => console.log(`observerA: ${v}`) + next: (v) => console.log(`observerA: ${v}`), }); subject.next(1); subject.next(2); subject.subscribe({ - next: (v) => console.log(`observerB: ${v}`) + next: (v) => console.log(`observerB: ${v}`), }); subject.next(3); @@ -240,7 +237,7 @@ subject.next(3); ## ReplaySubject -A `ReplaySubject` is similar to a `BehaviorSubject` in that it can send old values to new subscribers, but it can also *record* a part of the Observable execution. +A `ReplaySubject` is similar to a `BehaviorSubject` in that it can send old values to new subscribers, but it can also _record_ a part of the Observable execution. A `ReplaySubject` records multiple values from the Observable execution and replays them to new subscribers. @@ -251,7 +248,7 @@ import { ReplaySubject } from 'rxjs'; const subject = new ReplaySubject(3); // buffer 3 values for new subscribers subject.subscribe({ - next: (v) => console.log(`observerA: ${v}`) + next: (v) => console.log(`observerA: ${v}`), }); subject.next(1); @@ -260,7 +257,7 @@ subject.next(3); subject.next(4); subject.subscribe({ - next: (v) => console.log(`observerB: ${v}`) + next: (v) => console.log(`observerB: ${v}`), }); subject.next(5); @@ -277,15 +274,16 @@ subject.next(5); // observerB: 5 ``` -You can also specify a *window time* in milliseconds, besides of the buffer size, to determine how old the recorded values can be. In the following example we use a large buffer size of `100`, but a window time parameter of just `500` milliseconds. +You can also specify a _window time_ in milliseconds, besides of the buffer size, to determine how old the recorded values can be. In the following example we use a large buffer size of `100`, but a window time parameter of just `500` milliseconds. + ```ts import { ReplaySubject } from 'rxjs'; const subject = new ReplaySubject(100, 500 /* windowTime */); subject.subscribe({ - next: (v) => console.log(`observerA: ${v}`) + next: (v) => console.log(`observerA: ${v}`), }); let i = 1; @@ -293,7 +291,7 @@ setInterval(() => subject.next(i++), 200); setTimeout(() => { subject.subscribe({ - next: (v) => console.log(`observerB: ${v}`) + next: (v) => console.log(`observerB: ${v}`), }); }, 1000); @@ -320,7 +318,7 @@ import { AsyncSubject } from 'rxjs'; const subject = new AsyncSubject(); subject.subscribe({ - next: (v) => console.log(`observerA: ${v}`) + next: (v) => console.log(`observerA: ${v}`), }); subject.next(1); @@ -329,7 +327,7 @@ subject.next(3); subject.next(4); subject.subscribe({ - next: (v) => console.log(`observerB: ${v}`) + next: (v) => console.log(`observerB: ${v}`), }); subject.next(5); @@ -342,7 +340,6 @@ subject.complete(); The AsyncSubject is similar to the [`last()`](/api/operators/last) operator, in that it waits for the `complete` notification in order to deliver a single value. - ## Void subject Sometimes the emitted value doesn't matter as much as the fact that a value was emitted. @@ -371,10 +368,10 @@ import { Subject } from 'rxjs'; const subject = new Subject(); // Shorthand for Subject subject.subscribe({ - next: () => console.log('One second has passed') + next: () => console.log('One second has passed'), }); setTimeout(() => subject.next(), 1000); ``` -Before version 7, the default type of Subject values was `any`. `Subject` disables type checking of the emitted values, whereas `Subject` prevents accidental access to the emitted value. If you want the old behavior, then replace `Subject` with `Subject`. \ No newline at end of file +Before version 7, the default type of Subject values was `any`. `Subject` disables type checking of the emitted values, whereas `Subject` prevents accidental access to the emitted value. If you want the old behavior, then replace `Subject` with `Subject`. diff --git a/docs_app/content/guide/testing/marble-testing.md b/docs_app/content/guide/testing/marble-testing.md index 303f20330b..51e79878b3 100644 --- a/docs_app/content/guide/testing/marble-testing.md +++ b/docs_app/content/guide/testing/marble-testing.md @@ -10,7 +10,7 @@ We can test our _asynchronous_ RxJS code _synchronously_ and deterministically b ```ts import { TestScheduler } from 'rxjs/testing'; -import { throttleTime } from 'rxjs/operators'; +import { throttleTime } from 'rxjs'; const testScheduler = new TestScheduler((actual, expected) => { // asserting the two objects are equal - required diff --git a/docs_app/package.json b/docs_app/package.json index 87d09082f4..b5b72cb8de 100644 --- a/docs_app/package.json +++ b/docs_app/package.json @@ -116,7 +116,6 @@ "lighthouse": "^7.0.1", "lodash": "^4.17.20", "lunr": "^2.1.0", - "mkdirp": "^0.5.1", "protractor": "~7.0.0", "rehype-slug": "^2.0.3", "remark": "^12.0.1", diff --git a/docs_app/src/assets/images/marble-diagrams/audit.png b/docs_app/src/assets/images/marble-diagrams/audit.png deleted file mode 100644 index ceca809ff0..0000000000 Binary files a/docs_app/src/assets/images/marble-diagrams/audit.png and /dev/null differ diff --git a/docs_app/src/assets/images/marble-diagrams/debounce.png b/docs_app/src/assets/images/marble-diagrams/debounce.png deleted file mode 100644 index 91ed9bb1cf..0000000000 Binary files a/docs_app/src/assets/images/marble-diagrams/debounce.png and /dev/null differ diff --git a/docs_app/src/assets/images/marble-diagrams/throttle.png b/docs_app/src/assets/images/marble-diagrams/throttle.png deleted file mode 100644 index 18a69a0697..0000000000 Binary files a/docs_app/src/assets/images/marble-diagrams/throttle.png and /dev/null differ diff --git a/docs_app/tools/transforms/angular-api-package/index.js b/docs_app/tools/transforms/angular-api-package/index.js index 5217bb65c7..2cda9a5ba5 100644 --- a/docs_app/tools/transforms/angular-api-package/index.js +++ b/docs_app/tools/transforms/angular-api-package/index.js @@ -10,7 +10,7 @@ const Package = require('dgeni').Package; const basePackage = require('../angular-base-package'); const typeScriptPackage = require('dgeni-packages/typescript'); const { API_SOURCE_PATH, API_TEMPLATES_PATH, MARBLE_IMAGES_PATH, MARBLE_IMAGES_WEB_PATH, - MARBLE_IMAGES_OUTPUT_PATH, requireFolder } = require('../config'); + requireFolder } = require('../config'); module.exports = new Package('angular-api', [basePackage, typeScriptPackage]) @@ -188,15 +188,13 @@ module.exports = new Package('angular-api', [basePackage, typeScriptPackage]) .config(function(embedMarbleDiagramsPostProcessor) { embedMarbleDiagramsPostProcessor.marbleImagesPath = MARBLE_IMAGES_PATH; - embedMarbleDiagramsPostProcessor.marbleImagesOutputPath = MARBLE_IMAGES_OUTPUT_PATH; embedMarbleDiagramsPostProcessor.marbleImagesOutputWebPath = `/${MARBLE_IMAGES_WEB_PATH}`; }) .config(function(convertToJsonProcessor, postProcessHtml, API_DOC_TYPES_TO_RENDER, API_DOC_TYPES, autoLinkCode, embedMarbleDiagramsPostProcessor) { convertToJsonProcessor.docTypes = convertToJsonProcessor.docTypes.concat(API_DOC_TYPES_TO_RENDER); postProcessHtml.docTypes = convertToJsonProcessor.docTypes.concat(API_DOC_TYPES_TO_RENDER); - postProcessHtml.plugins = [embedMarbleDiagramsPostProcessor.process]; + postProcessHtml.plugins.push(embedMarbleDiagramsPostProcessor.process); autoLinkCode.docTypes = API_DOC_TYPES; autoLinkCode.codeElements = ['code', 'code-example', 'code-pane']; }); - diff --git a/docs_app/tools/transforms/angular-api-package/post-processors/embedMarbleDiagrams.js b/docs_app/tools/transforms/angular-api-package/post-processors/embedMarbleDiagrams.js index 7309502f33..266a762432 100644 --- a/docs_app/tools/transforms/angular-api-package/post-processors/embedMarbleDiagrams.js +++ b/docs_app/tools/transforms/angular-api-package/post-processors/embedMarbleDiagrams.js @@ -1,17 +1,14 @@ const fs = require('fs'); const path = require('path'); -const mkdirp = require('mkdirp'); const visit = require('unist-util-visit'); const is = require('hast-util-is-element'); /** * Find pre-rendered marble diagrams and override their `src` attributes in docs. - * You need to run `npm run tests2png` in rxjs root to generate marble diagrams into `tmp/docs/img` */ -module.exports = function embedMarbleDiagramsPostProcessor(log) { +module.exports = function embedMarbleDiagramsPostProcessor() { const service = { marbleImagesPath: null, - marbleImagesOutputPath: null, marbleImagesOutputWebPath: null, process: () => { return (tree) => { @@ -23,18 +20,12 @@ module.exports = function embedMarbleDiagramsPostProcessor(log) { if (fs.existsSync(expectedImgPath)) { const operator = path.basename(src, path.extname(src)); const filename = path.basename(expectedImgPath); - const targetPath = `${service.marbleImagesOutputPath}/${filename}`; - - mkdirp.sync(path.dirname(targetPath)); - fs.copyFileSync(expectedImgPath, targetPath); props.src = `${service.marbleImagesOutputWebPath}/${filename}`; props.width = '100%'; if (!props.alt) { props.alt = `${operator} marble diagram`; } - - log.debug(`Found ${expectedImgPath} and copying it to ${targetPath}`); } } }); diff --git a/docs_app/tools/transforms/angular-base-package/index.js b/docs_app/tools/transforms/angular-base-package/index.js index 85be858697..f42fff00c7 100644 --- a/docs_app/tools/transforms/angular-base-package/index.js +++ b/docs_app/tools/transforms/angular-base-package/index.js @@ -137,7 +137,7 @@ module.exports = new Package('angular-base', [ postProcessHtml.plugins = [ require('./post-processors/autolink-headings'), addImageDimensions, - require('./post-processors/h1-checker'), + // require('./post-processors/h1-checker'), autoLinkCode, ]; }) diff --git a/docs_app/tools/transforms/angular-base-package/post-processors/auto-link-code.js b/docs_app/tools/transforms/angular-base-package/post-processors/auto-link-code.js index 558a5705cb..18493f78da 100644 --- a/docs_app/tools/transforms/angular-base-package/post-processors/auto-link-code.js +++ b/docs_app/tools/transforms/angular-base-package/post-processors/auto-link-code.js @@ -24,56 +24,126 @@ module.exports = function autoLinkCode(getDocFromAlias) { autoLinkCodeImpl.docTypes = []; autoLinkCodeImpl.customFilters = []; autoLinkCodeImpl.codeElements = ['code']; + autoLinkCodeImpl.ignoredLanguages = ['bash', 'sh', 'shell', 'json', 'markdown']; + autoLinkCodeImpl.failOnMissingDocPath = false; + return autoLinkCodeImpl; - function autoLinkCodeImpl() { - return (ast) => { + function autoLinkCodeImpl() { + return (ast, file) => { visit(ast, 'element', (node, ancestors) => { - // Only interested in code elements that are not inside links - if (autoLinkCodeImpl.codeElements.some(elementType => is(node, elementType)) && - ancestors.every(ancestor => !is(ancestor, 'a'))) { - visit(node, 'text', (node, ancestors) => { - // Only interested in text nodes that are not inside links - if (ancestors.every(ancestor => !is(ancestor, 'a'))) { - - const parent = ancestors[ancestors.length-1]; - const index = parent.children.indexOf(node); - - // Can we convert the whole text node into a doc link? - const docs = getDocFromAlias(node.value); - if (foundValidDoc(docs)) { - parent.children.splice(index, 1, createLinkNode(docs[0], node.value)); - } else { - // Parse the text for words that we can convert to links - const nodes = textContent(node).split(/([A-Za-z0-9_.-]+)/) - .filter(word => word.length) - .map((word, index, words) => { - // remove docs that fail the custom filter tests - const filteredDocs = autoLinkCodeImpl.customFilters.reduce((docs, filter) => filter(docs, words, index), getDocFromAlias(word)); - return foundValidDoc(filteredDocs) ? - createLinkNode(filteredDocs[0], word) : // Create a link wrapping the text node. - { type: 'text', value: word }; // this is just text so push a new text node - }); - - // Replace the text node with the links and leftover text nodes - Array.prototype.splice.apply(parent.children, [index, 1].concat(nodes)); - } - } - }); + if (!isValidCodeElement(node, ancestors)) { + return; } + + visit(node, 'text', (node, ancestors) => { + const isInLink = isInsideLink(ancestors); + if (isInLink) { + return; + } + + const parent = ancestors[ancestors.length - 1]; + const index = parent.children.indexOf(node); + + // Can we convert the whole text node into a doc link? + const docs = getFilteredDocsFromAlias([node.value], 0); + if (foundValidDoc(docs, node.value, file)) { + parent.children.splice(index, 1, createLinkNode(docs[0], node.value)); + } else { + // Parse the text for words that we can convert to links + const nodes = getNodes(node, file); + // Replace the text node with the links and leftover text nodes + Array.prototype.splice.apply(parent.children, [index, 1].concat(nodes)); + // Do not visit this node's children or the newly added nodes + return [visit.SKIP, index + nodes.length]; + } + }); }); }; } - function foundValidDoc(docs) { - return docs.length === 1 && autoLinkCodeImpl.docTypes.indexOf(docs[0].docType) !== -1; + + function isValidCodeElement(node, ancestors) { + // Only interested in code elements that: + // * do not have `no-auto-link` class + // * do not have an ignored language + // * are not inside links + const isCodeElement = autoLinkCodeImpl.codeElements.some(elementType => is(node, elementType)); + const hasNoAutoLink = + node.properties.className && node.properties.className.includes('no-auto-link'); + const isLanguageSupported = + !autoLinkCodeImpl.ignoredLanguages.includes(node.properties.language); + const isInLink = isInsideLink(ancestors); + return isCodeElement && !hasNoAutoLink && isLanguageSupported && !isInLink; + } + + function isInsideLink(ancestors) { + return ancestors.some(ancestor => is(ancestor, 'a')); + } + + function getFilteredDocsFromAlias(words, index) { + // Remove docs that fail the custom filter tests. + return autoLinkCodeImpl.customFilters.reduce( + (docs, filter) => filter(docs, words, index), getDocFromAlias(words[index])); + } + + function getNodes(node, file) { + return textContent(node) + .split(/([A-Za-z0-9_.-]+)/) + .filter(word => word.length) + .map((word, index, words) => { + const filteredDocs = getFilteredDocsFromAlias(words, index); + + return foundValidDoc(filteredDocs, word, file) ? + // Create a link wrapping the text node. + createLinkNode(filteredDocs[0], word) : + // this is just text so push a new text node + {type: 'text', value: word}; + }); + } + + /** + * Validates the docs to be used to generate the links. The validation ensures + * that the docs are not `internal` and that the `docType` is supported. The `path` + * can be empty when the `API` is not public. + * + * @param {Array} docs An array of objects containing the doc details + * + * @param {string} keyword The keyword the doc applies to + */ + function foundValidDoc(docs, keyword, file) { + if (docs.length !== 1) { + return false; + } + + var doc = docs[0]; + + const isInvalidDoc = doc.docType === 'member' && !keyword.includes('.'); + if (isInvalidDoc) { + return false; + } + + if (!doc.path) { + var message = ` + autoLinkCode: Doc path is empty for "${doc.id}" - link will not be generated for "${keyword}". + Please make sure if the doc should be public. If not, it should probably not be referenced in the docs.`; + + if (autoLinkCodeImpl.failOnMissingDocPath) { + file.fail(message); + } else { + file.message(message); + } + return false; + } + + return !doc.internal && autoLinkCodeImpl.docTypes.includes(doc.docType); } function createLinkNode(doc, text) { return { type: 'element', tagName: 'a', - properties: { href: doc.path, class: 'code-anchor' }, - children: [{ type: 'text', value: text }] + properties: {href: doc.path, class: 'code-anchor'}, + children: [{type: 'text', value: text}] }; } }; diff --git a/docs_app/tools/transforms/config.js b/docs_app/tools/transforms/config.js index 2c1fa9305b..ed275de6f1 100644 --- a/docs_app/tools/transforms/config.js +++ b/docs_app/tools/transforms/config.js @@ -12,7 +12,6 @@ const DOCS_OUTPUT_PATH = resolve(OUTPUT_PATH, 'docs'); const API_SOURCE_PATH = resolve(PROJECT_ROOT, 'src'); const MARBLE_IMAGES_PATH = resolve(SRC_PATH, 'assets/images/marble-diagrams'); const MARBLE_IMAGES_WEB_PATH = 'assets/images/marble-diagrams'; -const MARBLE_IMAGES_OUTPUT_PATH = resolve('assets/images/marble-diagrams'); function requireFolder(dirname, folderPath) { const absolutePath = resolve(dirname, folderPath); @@ -22,5 +21,5 @@ function requireFolder(dirname, folderPath) { } module.exports = { PROJECT_ROOT, AIO_PATH, TEMPLATES_PATH, API_TEMPLATES_PATH, CONTENTS_PATH, SRC_PATH, - OUTPUT_PATH, DOCS_OUTPUT_PATH, API_SOURCE_PATH, MARBLE_IMAGES_PATH, MARBLE_IMAGES_OUTPUT_PATH, MARBLE_IMAGES_WEB_PATH, requireFolder }; + OUTPUT_PATH, DOCS_OUTPUT_PATH, API_SOURCE_PATH, MARBLE_IMAGES_PATH, MARBLE_IMAGES_WEB_PATH, requireFolder }; diff --git a/docs_app/tools/transforms/links-package/services/disambiguators/disambiguateByNonOperator.js b/docs_app/tools/transforms/links-package/services/disambiguators/disambiguateByNonOperator.js index 8fdb5538ad..da066374b7 100644 --- a/docs_app/tools/transforms/links-package/services/disambiguators/disambiguateByNonOperator.js +++ b/docs_app/tools/transforms/links-package/services/disambiguators/disambiguateByNonOperator.js @@ -5,7 +5,7 @@ */ module.exports = function disambiguateByNonOperator() { return (alias, originatingDoc, docs) => { - const filteredDocs = docs.filter((doc) => doc.moduleDoc.id !== 'operators'); + const filteredDocs = docs.filter((doc) => doc.moduleDoc?.id !== 'operators'); return filteredDocs.length > 0 ? filteredDocs : docs; }; }; diff --git a/integration/side-effects/snapshots/esm/ajax.js b/integration/side-effects/snapshots/esm/ajax.js index 5d63e0559f..8b13789179 100644 --- a/integration/side-effects/snapshots/esm/ajax.js +++ b/integration/side-effects/snapshots/esm/ajax.js @@ -1 +1 @@ -import "tslib"; + diff --git a/package-lock.json b/package-lock.json index 89d8ef76bf..bcb0d69f6f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "rxjs", - "version": "7.5.0", + "version": "7.5.1", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "rxjs", - "version": "7.5.0", + "version": "7.5.1", "license": "Apache-2.0", "dependencies": { "tslib": "^2.1.0" @@ -44,13 +44,12 @@ "lint-staged": "^10.2.11", "lodash": "^4.17.15", "minimist": "^1.2.5", - "mkdirp": "^1.0.4", "mocha": "^8.1.3", "nodemon": "^1.9.2", "npm-run-all": "4.1.2", "opn-cli": "3.1.0", "platform": "1.3.5", - "prettier": "^2.0.5", + "prettier": "^2.5.1", "promise": "8.0.1", "rollup": "0.66.6", "rollup-plugin-alias": "1.4.0", @@ -69,7 +68,6 @@ "tslint-etc": "1.13.10", "tslint-no-toplevel-property-access": "0.0.2", "tslint-no-unused-expression-chai": "0.0.3", - "typedoc": "^0.17.8", "typescript": "~4.2.0", "validate-commit-msg": "2.14.0", "web-streams-polyfill": "^3.0.2", @@ -2643,7 +2641,7 @@ "version": "2.6.9", "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.6.9.tgz", "integrity": "sha512-HOpZf6eXmnl7la+cUdMnLvUxKNqLUzJvgIziQ0DiF3JwSImNphIqdGqzj6hIKyX04MmV0poclQ7+wjWvxQyR2A==", - "deprecated": "core-js@<3.3 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whims, feature detection in old core-js versions could cause a slowdown up to 100x even if nothing is polyfilled. Please, upgrade your dependencies to the actual version of core-js.", + "deprecated": "core-js@<3.4 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whims, feature detection in old core-js versions could cause a slowdown up to 100x even if nothing is polyfilled. Please, upgrade your dependencies to the actual version of core-js.", "dev": true, "hasInstallScript": true }, @@ -5175,15 +5173,6 @@ "he": "bin/he" } }, - "node_modules/highlight.js": { - "version": "10.4.1", - "resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-10.4.1.tgz", - "integrity": "sha512-yR5lWvNz7c85OhVAEAeFhVCc/GV4C30Fjzc/rCP0aCWzc1UUOPUk55dK/qdwTZHBvMZo+eZ2jpk62ndX/xMFlg==", - "dev": true, - "engines": { - "node": "*" - } - }, "node_modules/hmac-drbg": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/hmac-drbg/-/hmac-drbg-1.0.1.tgz", @@ -7083,12 +7072,6 @@ "yallist": "^2.1.2" } }, - "node_modules/lunr": { - "version": "2.3.8", - "resolved": "https://registry.npmjs.org/lunr/-/lunr-2.3.8.tgz", - "integrity": "sha512-oxMeX/Y35PNFuZoHp+jUj5OSEmLCaIH4KTFJh7a93cHBoFmpw2IoPs22VIz7vyO2YUnx2Tn9dzIwO2P/4quIRg==", - "dev": true - }, "node_modules/magic-string": { "version": "0.16.0", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.16.0.tgz", @@ -7177,18 +7160,6 @@ "node": ">=0.10.0" } }, - "node_modules/marked": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/marked/-/marked-1.0.0.tgz", - "integrity": "sha512-Wo+L1pWTVibfrSr+TTtMuiMfNzmZWiOPeO7rZsQUY5bgsxpHesBEcIWJloWVTFnrMXnf/TL30eTFSGJddmQAng==", - "dev": true, - "bin": { - "marked": "bin/marked" - }, - "engines": { - "node": ">= 8.16.2" - } - }, "node_modules/md5.js": { "version": "1.3.5", "resolved": "https://registry.npmjs.org/md5.js/-/md5.js-1.3.5.tgz", @@ -7398,18 +7369,6 @@ "node": ">=0.10.0" } }, - "node_modules/mkdirp": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", - "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", - "dev": true, - "bin": { - "mkdirp": "bin/cmd.js" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/mocha": { "version": "8.1.3", "resolved": "https://registry.npmjs.org/mocha/-/mocha-8.1.3.tgz", @@ -8884,9 +8843,9 @@ } }, "node_modules/prettier": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.0.5.tgz", - "integrity": "sha512-7PtVymN48hGcO4fGjybyBSIWDsLU4H4XlvOHfq91pz9kkGlonzwTfYkaIEwiRg/dAJF9YlbsduBAgtYLi+8cFg==", + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.5.1.tgz", + "integrity": "sha512-vBZcPRUR5MZJwoyi3ZoyQlc1rXeEck8KgeC9AwwOn+exuxLxq5toTRDTSaVrXHxelDMHy9zlicw8u66yxoSUFg==", "dev": true, "bin": { "prettier": "bin-prettier.js" @@ -11901,45 +11860,6 @@ "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=", "dev": true }, - "node_modules/typedoc": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/typedoc/-/typedoc-0.17.8.tgz", - "integrity": "sha512-/OyrHCJ8jtzu+QZ+771YaxQ9s4g5Z3XsQE3Ma7q+BL392xxBn4UMvvCdVnqKC2T/dz03/VXSLVKOP3lHmDdc/w==", - "dev": true, - "dependencies": { - "fs-extra": "^8.1.0", - "handlebars": "^4.7.6", - "highlight.js": "^10.0.0", - "lodash": "^4.17.15", - "lunr": "^2.3.8", - "marked": "1.0.0", - "minimatch": "^3.0.0", - "progress": "^2.0.3", - "shelljs": "^0.8.4", - "typedoc-default-themes": "^0.10.2" - }, - "bin": { - "typedoc": "bin/typedoc" - }, - "engines": { - "node": ">= 8.0.0" - }, - "peerDependencies": { - "typescript": ">=3.8.3" - } - }, - "node_modules/typedoc-default-themes": { - "version": "0.10.2", - "resolved": "https://registry.npmjs.org/typedoc-default-themes/-/typedoc-default-themes-0.10.2.tgz", - "integrity": "sha512-zo09yRj+xwLFE3hyhJeVHWRSPuKEIAsFK5r2u47KL/HBKqpwdUSanoaz5L34IKiSATFrjG5ywmIu98hPVMfxZg==", - "dev": true, - "dependencies": { - "lunr": "^2.3.8" - }, - "engines": { - "node": ">= 8" - } - }, "node_modules/typescript": { "version": "4.2.4", "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.2.4.tgz", @@ -16989,12 +16909,6 @@ "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", "dev": true }, - "highlight.js": { - "version": "10.4.1", - "resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-10.4.1.tgz", - "integrity": "sha512-yR5lWvNz7c85OhVAEAeFhVCc/GV4C30Fjzc/rCP0aCWzc1UUOPUk55dK/qdwTZHBvMZo+eZ2jpk62ndX/xMFlg==", - "dev": true - }, "hmac-drbg": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/hmac-drbg/-/hmac-drbg-1.0.1.tgz", @@ -18449,12 +18363,6 @@ "yallist": "^2.1.2" } }, - "lunr": { - "version": "2.3.8", - "resolved": "https://registry.npmjs.org/lunr/-/lunr-2.3.8.tgz", - "integrity": "sha512-oxMeX/Y35PNFuZoHp+jUj5OSEmLCaIH4KTFJh7a93cHBoFmpw2IoPs22VIz7vyO2YUnx2Tn9dzIwO2P/4quIRg==", - "dev": true - }, "magic-string": { "version": "0.16.0", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.16.0.tgz", @@ -18527,12 +18435,6 @@ "object-visit": "^1.0.0" } }, - "marked": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/marked/-/marked-1.0.0.tgz", - "integrity": "sha512-Wo+L1pWTVibfrSr+TTtMuiMfNzmZWiOPeO7rZsQUY5bgsxpHesBEcIWJloWVTFnrMXnf/TL30eTFSGJddmQAng==", - "dev": true - }, "md5.js": { "version": "1.3.5", "resolved": "https://registry.npmjs.org/md5.js/-/md5.js-1.3.5.tgz", @@ -18708,12 +18610,6 @@ } } }, - "mkdirp": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", - "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", - "dev": true - }, "mocha": { "version": "8.1.3", "resolved": "https://registry.npmjs.org/mocha/-/mocha-8.1.3.tgz", @@ -19870,9 +19766,9 @@ "dev": true }, "prettier": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.0.5.tgz", - "integrity": "sha512-7PtVymN48hGcO4fGjybyBSIWDsLU4H4XlvOHfq91pz9kkGlonzwTfYkaIEwiRg/dAJF9YlbsduBAgtYLi+8cFg==", + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.5.1.tgz", + "integrity": "sha512-vBZcPRUR5MZJwoyi3ZoyQlc1rXeEck8KgeC9AwwOn+exuxLxq5toTRDTSaVrXHxelDMHy9zlicw8u66yxoSUFg==", "dev": true }, "process": { @@ -22247,33 +22143,6 @@ "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=", "dev": true }, - "typedoc": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/typedoc/-/typedoc-0.17.8.tgz", - "integrity": "sha512-/OyrHCJ8jtzu+QZ+771YaxQ9s4g5Z3XsQE3Ma7q+BL392xxBn4UMvvCdVnqKC2T/dz03/VXSLVKOP3lHmDdc/w==", - "dev": true, - "requires": { - "fs-extra": "^8.1.0", - "handlebars": "^4.7.6", - "highlight.js": "^10.0.0", - "lodash": "^4.17.15", - "lunr": "^2.3.8", - "marked": "1.0.0", - "minimatch": "^3.0.0", - "progress": "^2.0.3", - "shelljs": "^0.8.4", - "typedoc-default-themes": "^0.10.2" - } - }, - "typedoc-default-themes": { - "version": "0.10.2", - "resolved": "https://registry.npmjs.org/typedoc-default-themes/-/typedoc-default-themes-0.10.2.tgz", - "integrity": "sha512-zo09yRj+xwLFE3hyhJeVHWRSPuKEIAsFK5r2u47KL/HBKqpwdUSanoaz5L34IKiSATFrjG5ywmIu98hPVMfxZg==", - "dev": true, - "requires": { - "lunr": "^2.3.8" - } - }, "typescript": { "version": "4.2.4", "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.2.4.tgz", diff --git a/package.json b/package.json index 58c418eca8..f96f55a124 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "rxjs", - "version": "7.5.1", + "version": "7.5.2", "description": "Reactive Extensions for modern JavaScript", "main": "./dist/cjs/index.js", "module": "./dist/esm5/index.js", @@ -175,13 +175,12 @@ "lint-staged": "^10.2.11", "lodash": "^4.17.15", "minimist": "^1.2.5", - "mkdirp": "^1.0.4", "mocha": "^8.1.3", "nodemon": "^1.9.2", "npm-run-all": "4.1.2", "opn-cli": "3.1.0", "platform": "1.3.5", - "prettier": "^2.0.5", + "prettier": "^2.5.1", "promise": "8.0.1", "rollup": "0.66.6", "rollup-plugin-alias": "1.4.0", @@ -200,7 +199,6 @@ "tslint-etc": "1.13.10", "tslint-no-toplevel-property-access": "0.0.2", "tslint-no-unused-expression-chai": "0.0.3", - "typedoc": "^0.17.8", "typescript": "~4.2.0", "validate-commit-msg": "2.14.0", "web-streams-polyfill": "^3.0.2", diff --git a/spec/Observable-spec.ts b/spec/Observable-spec.ts index f5cd8ad5f1..630cd5085d 100644 --- a/spec/Observable-spec.ts +++ b/spec/Observable-spec.ts @@ -30,11 +30,9 @@ describe('Observable', () => { }); source.subscribe( - function (x) { + { next: function (x) { expect(x).to.equal(1); - }, - null, - done + }, complete: done } ); }); @@ -211,15 +209,13 @@ describe('Observable', () => { let mutatedByComplete = false; source.subscribe( - (x) => { + { next: (x) => { nexted = x; mutatedByNext = true; - }, - null, - () => { + }, complete: () => { completed = true; mutatedByComplete = true; - } + } } ); expect(mutatedByNext).to.be.true; @@ -382,14 +378,13 @@ describe('Observable', () => { }) .pipe(tap(() => (times += 1))) .subscribe( - function () { + { next: function () { if (times === 2) { subscription.unsubscribe(); } - }, - function () { + }, error: function () { errorCalled = true; - } + } } ); }); @@ -415,15 +410,13 @@ describe('Observable', () => { }) .pipe(tap(() => (times += 1))) .subscribe( - function () { + { next: function () { if (times === 2) { subscription.unsubscribe(); } - }, - null, - function () { + }, complete: function () { completeCalled = true; - } + } } ); }); @@ -847,11 +840,9 @@ describe('Observable', () => { map((x) => x + '!!!') ) .subscribe( - (x) => { + { next: (x) => { expect(x).to.equal('testtest!!!'); - }, - null, - done + }, complete: done } ); }); @@ -1006,15 +997,13 @@ describe('Observable.lift', () => { const expected = [10, 20, 30]; result.subscribe( - function (x) { + { next: function (x) { expect(x).to.equal(expected.shift()); - }, - () => { + }, error: () => { done(new Error('should not be called')); - }, - () => { + }, complete: () => { done(); - } + } } ); }); @@ -1035,15 +1024,13 @@ describe('Observable.lift', () => { const expected = [10, 20, 30]; result.subscribe( - function (x) { + { next: function (x) { expect(x).to.equal(expected.shift()); - }, - () => { + }, error: () => { done(new Error('should not be called')); - }, - () => { + }, complete: () => { done(); - } + } } ); }); @@ -1065,15 +1052,13 @@ describe('Observable.lift', () => { const expected = [10, 20, 30]; result.subscribe( - function (x) { + { next: function (x) { expect(x).to.equal(expected.shift()); - }, - () => { + }, error: () => { done(new Error('should not be called')); - }, - () => { + }, complete: () => { done(); - } + } } ); }); @@ -1095,15 +1080,13 @@ describe('Observable.lift', () => { const expected = [30]; result.subscribe( - function (x) { + { next: function (x) { expect(x).to.equal(expected.shift()); - }, - () => { + }, error: () => { done(new Error('should not be called')); - }, - () => { + }, complete: () => { done(); - } + } } ); }); @@ -1124,15 +1107,13 @@ describe('Observable.lift', () => { const expected = [0, 10, 20, 30]; result.subscribe( - function (x) { + { next: function (x) { expect(x).to.equal(expected.shift()); - }, - () => { + }, error: () => { done(new Error('should not be called')); - }, - () => { + }, complete: () => { done(); - } + } } ); }); @@ -1308,15 +1289,13 @@ describe('Observable.lift', () => { const expected = [10, 20, 30]; result.subscribe( - function (x) { + { next: function (x) { expect(x).to.equal(expected.shift()); - }, - () => { + }, error: () => { done(new Error('should not be called')); - }, - () => { + }, complete: () => { done(); - } + } } ); }); @@ -1458,13 +1437,11 @@ describe('Observable.lift', () => { const expected = [2]; result.subscribe( - function (x) { + { next: function (x) { expect(x).to.equal(expected.shift()); - }, - () => { + }, error: () => { done(new Error('should not be called')); - }, - () => { + }, complete: () => { expect(log).to.deep.equal([ 'next 10', // map 'next 20', // map @@ -1474,7 +1451,7 @@ describe('Observable.lift', () => { 'next 2', // count ]); done(); - } + } } ); }); }); diff --git a/spec/Subject-spec.ts b/spec/Subject-spec.ts index 3f922456ee..f6f68153bd 100644 --- a/spec/Subject-spec.ts +++ b/spec/Subject-spec.ts @@ -16,11 +16,9 @@ describe('Subject', () => { it('should allow next with undefined or any when created with no type', (done) => { const subject = new Subject(); subject.subscribe( - (x) => { + { next: (x) => { expect(x).to.be.a('undefined'); - }, - null, - done + }, complete: done } ); const data: any = undefined; @@ -32,11 +30,9 @@ describe('Subject', () => { it('should allow empty next when created with void type', (done) => { const subject = new Subject(); subject.subscribe( - (x) => { + { next: (x) => { expect(x).to.be.a('undefined'); - }, - null, - done + }, complete: done } ); subject.next(); @@ -48,11 +44,9 @@ describe('Subject', () => { const expected = ['foo', 'bar']; subject.subscribe( - (x: string) => { + { next: (x: string) => { expect(x).to.equal(expected.shift()); - }, - null, - done + }, complete: done } ); subject.next('foo'); @@ -72,11 +66,9 @@ describe('Subject', () => { }); subject.subscribe( - function (x) { + { next: function (x) { expect(x).to.equal(expected[j++]); - }, - null, - done + }, complete: done } ); expect(subject.observers.length).to.equal(2); @@ -97,29 +89,25 @@ describe('Subject', () => { subject.next(4); const subscription1 = subject.subscribe( - function (x) { + { next: function (x) { results1.push(x); - }, - function (e) { + }, error: function (e) { results1.push('E'); - }, - () => { + }, complete: () => { results1.push('C'); - } + } } ); subject.next(5); const subscription2 = subject.subscribe( - function (x) { + { next: function (x) { results2.push(x); - }, - function (e) { + }, error: function (e) { results2.push('E'); - }, - () => { + }, complete: () => { results2.push('C'); - } + } } ); subject.next(6); @@ -135,15 +123,13 @@ describe('Subject', () => { subject.next(10); const subscription3 = subject.subscribe( - function (x) { + { next: function (x) { results3.push(x); - }, - function (e) { + }, error: function (e) { results3.push('E'); - }, - () => { + }, complete: () => { results3.push('C'); - } + } } ); subject.next(11); @@ -167,29 +153,25 @@ describe('Subject', () => { subject.next(4); const subscription1 = subject.subscribe( - function (x) { + { next: function (x) { results1.push(x); - }, - function (e) { + }, error: function (e) { results1.push('E'); - }, - () => { + }, complete: () => { results1.push('C'); - } + } } ); subject.next(5); const subscription2 = subject.subscribe( - function (x) { + { next: function (x) { results2.push(x); - }, - function (e) { + }, error: function (e) { results2.push('E'); - }, - () => { + }, complete: () => { results2.push('C'); - } + } } ); subject.next(6); @@ -202,15 +184,13 @@ describe('Subject', () => { subscription2.unsubscribe(); const subscription3 = subject.subscribe( - function (x) { + { next: function (x) { results3.push(x); - }, - function (e) { + }, error: function (e) { results3.push('E'); - }, - () => { + }, complete: () => { results3.push('C'); - } + } } ); subscription3.unsubscribe(); @@ -232,29 +212,25 @@ describe('Subject', () => { subject.next(4); const subscription1 = subject.subscribe( - function (x) { + { next: function (x) { results1.push(x); - }, - function (e) { + }, error: function (e) { results1.push('E'); - }, - () => { + }, complete: () => { results1.push('C'); - } + } } ); subject.next(5); const subscription2 = subject.subscribe( - function (x) { + { next: function (x) { results2.push(x); - }, - function (e) { + }, error: function (e) { results2.push('E'); - }, - () => { + }, complete: () => { results2.push('C'); - } + } } ); subject.next(6); @@ -267,15 +243,13 @@ describe('Subject', () => { subscription2.unsubscribe(); const subscription3 = subject.subscribe( - function (x) { + { next: function (x) { results3.push(x); - }, - function (e) { + }, error: function (e) { results3.push('E'); - }, - () => { + }, complete: () => { results3.push('C'); - } + } } ); subscription3.unsubscribe(); @@ -292,27 +266,23 @@ describe('Subject', () => { const results3: (number | string)[] = []; const subscription1 = subject.subscribe( - function (x) { + { next: function (x) { results1.push(x); - }, - function (e) { + }, error: function (e) { results1.push('E'); - }, - () => { + }, complete: () => { results1.push('C'); - } + } } ); const subscription2 = subject.subscribe( - function (x) { + { next: function (x) { results2.push(x); - }, - function (e) { + }, error: function (e) { results2.push('E'); - }, - () => { + }, complete: () => { results2.push('C'); - } + } } ); subscription1.unsubscribe(); @@ -322,15 +292,13 @@ describe('Subject', () => { subscription2.unsubscribe(); const subscription3 = subject.subscribe( - function (x) { + { next: function (x) { results3.push(x); - }, - function (e) { + }, error: function (e) { results3.push('E'); - }, - () => { + }, complete: () => { results3.push('C'); - } + } } ); subscription3.unsubscribe(); @@ -347,30 +315,26 @@ describe('Subject', () => { const results3: (number | string)[] = []; const subscription1 = subject.subscribe( - function (x) { + { next: function (x) { results1.push(x); - }, - function (e) { + }, error: function (e) { results1.push('E'); - }, - () => { + }, complete: () => { results1.push('C'); - } + } } ); subject.next(1); subject.next(2); const subscription2 = subject.subscribe( - function (x) { + { next: function (x) { results2.push(x); - }, - function (e) { + }, error: function (e) { results2.push('E'); - }, - () => { + }, complete: () => { results2.push('C'); - } + } } ); subject.next(3); @@ -383,12 +347,11 @@ describe('Subject', () => { expect(() => { subject.subscribe( - function (x) { + { next: function (x) { results3.push(x); - }, - function (err) { + }, error: function (err) { expect(false).to.equal('should not throw error: ' + err.toString()); - } + } } ); }).to.throw(ObjectUnsubscribedError); @@ -560,15 +523,13 @@ describe('Subject', () => { const expected = [1, 2, 3, 4, 5]; subject.subscribe( - function (x) { + { next: function (x) { expect(x).to.equal(expected.shift()); - }, - (x) => { + }, error: (x) => { done(new Error('should not be called')); - }, - () => { + }, complete: () => { done(); - } + } } ); source.subscribe(subject); @@ -581,15 +542,13 @@ describe('Subject', () => { const expected = [1, 2, 3]; subject.subscribe( - function (x) { + { next: function (x) { expect(x).to.equal(expected.shift()); - }, - (x) => { + }, error: (x) => { done(new Error('should not be called')); - }, - () => { + }, complete: () => { done(); - } + } } ); source.subscribe(subject); @@ -616,9 +575,7 @@ describe('Subject', () => { const subject = new Subject(); const results: string[] = []; subject.subscribe( - (x) => results.push(x), - null, - () => results.push('C') + { next: (x) => results.push(x), complete: () => results.push('C') } ); subject.next('a'); subject.complete(); @@ -631,8 +588,7 @@ describe('Subject', () => { const subject = new Subject(); const results: string[] = []; subject.subscribe( - (x) => results.push(x), - (err) => results.push(err) + { next: (x) => results.push(x), error: (err) => results.push(err) } ); subject.next('a'); subject.error(error); @@ -696,9 +652,7 @@ describe('Subject', () => { const observable = subject.asObservable(); observable.subscribe( - (x) => results.push(x), - null, - () => results.push('done') + { next: (x) => results.push(x), complete: () => results.push('done') } ); expect(results).to.deep.equal([42, 'done']); diff --git a/spec/observables/bindCallback-spec.ts b/spec/observables/bindCallback-spec.ts index 60a16cedd4..00585a7b79 100644 --- a/spec/observables/bindCallback-spec.ts +++ b/spec/observables/bindCallback-spec.ts @@ -16,11 +16,11 @@ describe('bindCallback', () => { const results: Array = []; boundCallback() - .subscribe((x: any) => { + .subscribe({ next: (x: any) => { results.push(typeof x); - }, null, () => { + }, complete: () => { results.push('done'); - }); + } }); expect(results).to.deep.equal(['undefined', 'done']); }); @@ -75,11 +75,11 @@ describe('bindCallback', () => { const results: Array = []; boundCallback(42) - .subscribe(x => { + .subscribe({ next: x => { results.push(x); - }, null, () => { + }, complete: () => { results.push('done'); - }); + } }); expect(results).to.deep.equal([42, 'done']); }); @@ -94,9 +94,7 @@ describe('bindCallback', () => { boundCallback.apply({datum: 5}) .subscribe( - (x: number) => results.push(x), - null, - () => results.push('done') + { next: (x: number) => results.push(x), complete: () => results.push('done') } ); expect(results).to.deep.equal([5, 'done']); @@ -114,7 +112,7 @@ describe('bindCallback', () => { }, 0); } const subscription = bindCallback(callback)(42) - .subscribe(nextSpy, throwSpy, completeSpy); + .subscribe({ next: nextSpy, error: throwSpy, complete: completeSpy }); subscription.unsubscribe(); setTimeout(() => { @@ -135,17 +133,17 @@ describe('bindCallback', () => { const results: Array = []; boundCallback(42) - .subscribe(x => { + .subscribe({ next: x => { results.push(x); - }, null, () => { + }, complete: () => { results.push('done'); - }); + } }); boundCallback(54) - .subscribe(x => { + .subscribe({ next: x => { results.push(x); - }, null, () => { + }, complete: () => { results.push('done'); - }); + } }); expect(results).to.deep.equal([42, 'done', 54, 'done']); }); @@ -160,11 +158,11 @@ describe('bindCallback', () => { const results: Array = []; boundCallback() - .subscribe(x => { + .subscribe({ next: x => { results.push(typeof x); - }, null, () => { + }, complete: () => { results.push('done'); - }); + } }); rxTestScheduler.flush(); @@ -179,11 +177,11 @@ describe('bindCallback', () => { const results: Array = []; boundCallback(42) - .subscribe(x => { + .subscribe({ next: x => { results.push(x); - }, null, () => { + }, complete: () => { results.push('done'); - }); + } }); rxTestScheduler.flush(); @@ -200,9 +198,7 @@ describe('bindCallback', () => { boundCallback.apply({ datum: 5 }) .subscribe( - (x: number) => results.push(x), - null, - () => results.push('done') + { next: (x: number) => results.push(x), complete: () => results.push('done') } ); rxTestScheduler.flush(); @@ -218,13 +214,13 @@ describe('bindCallback', () => { const boundCallback = bindCallback(callback, rxTestScheduler); boundCallback(42) - .subscribe(x => { + .subscribe({ next: x => { throw new Error('should not next'); - }, (err: any) => { + }, error: (err: any) => { expect(err).to.equal(expected); - }, () => { + }, complete: () => { throw new Error('should not complete'); - }); + } }); rxTestScheduler.flush(); }); @@ -237,11 +233,11 @@ describe('bindCallback', () => { const results: Array = []; boundCallback(42) - .subscribe(x => { + .subscribe({ next: x => { results.push(x); - }, null, () => { + }, complete: () => { results.push('done'); - }); + } }); rxTestScheduler.flush(); @@ -260,17 +256,17 @@ describe('bindCallback', () => { const source = boundCallback(42); - source.subscribe(x => { + source.subscribe({ next: x => { results1.push(x); - }, null, () => { + }, complete: () => { results1.push('done'); - }); + } }); - source.subscribe(x => { + source.subscribe({ next: x => { results2.push(x); - }, null, () => { + }, complete: () => { results2.push('done'); - }); + } }); rxTestScheduler.flush(); @@ -290,11 +286,11 @@ describe('bindCallback', () => { const source = boundCallback(42); - const subscription = source.subscribe((x: any) => { + const subscription = source.subscribe({ next: (x: any) => { results1.push(x); - }, null, () => { + }, complete: () => { results1.push('done'); - }); + } }); subscription.unsubscribe(); diff --git a/spec/observables/bindNodeCallback-spec.ts b/spec/observables/bindNodeCallback-spec.ts index c3cd890662..a264f58041 100644 --- a/spec/observables/bindNodeCallback-spec.ts +++ b/spec/observables/bindNodeCallback-spec.ts @@ -17,11 +17,11 @@ describe('bindNodeCallback', () => { const results: Array = []; boundCallback() - .subscribe((x: any) => { + .subscribe({ next: (x: any) => { results.push(typeof x); - }, null, () => { + }, complete: () => { results.push('done'); - }); + } }); expect(results).to.deep.equal(['undefined', 'done']); }); @@ -35,11 +35,11 @@ describe('bindNodeCallback', () => { const results: Array = []; boundCallback() - .subscribe(x => { + .subscribe({ next: x => { results.push(x); - }, null, () => { + }, complete: () => { results.push('done'); - }); + } }); expect(results).to.deep.equal([43, 'done']); }); @@ -52,11 +52,11 @@ describe('bindNodeCallback', () => { const results: Array = []; boundCallback(42) - .subscribe(x => { + .subscribe({ next: x => { results.push(x); - }, null, () => { + }, complete: () => { results.push('done'); - }); + } }); expect(results).to.deep.equal([42, 'done']); }); @@ -70,9 +70,7 @@ describe('bindNodeCallback', () => { boundCallback.call({datum: 42}) .subscribe( - (x: number) => results.push(x), - null, - () => results.push('done') + { next: (x: number) => results.push(x), complete: () => results.push('done') } ); expect(results).to.deep.equal([42, 'done']); @@ -89,13 +87,13 @@ describe('bindNodeCallback', () => { const results: Array = []; boundCallback() - .subscribe(() => { + .subscribe({ next: () => { throw new Error('should not next'); - }, (err: any) => { + }, error: (err: any) => { results.push(err); - }, () => { + }, complete: () => { throw new Error('should not complete'); - }); + } }); expect(results).to.deep.equal([error]); }); @@ -112,7 +110,7 @@ describe('bindNodeCallback', () => { }, 0); } const subscription = bindNodeCallback(callback)(42) - .subscribe(nextSpy, throwSpy, completeSpy); + .subscribe({ next: nextSpy, error: throwSpy, complete: completeSpy }); subscription.unsubscribe(); setTimeout(() => { @@ -133,17 +131,17 @@ describe('bindNodeCallback', () => { const results: Array = []; boundCallback(42) - .subscribe(x => { + .subscribe({ next: x => { results.push(x); - }, null, () => { + }, complete: () => { results.push('done'); - }); + } }); boundCallback(54) - .subscribe(x => { + .subscribe({ next: x => { results.push(x); - }, null, () => { + }, complete: () => { results.push('done'); - }); + } }); expect(results).to.deep.equal([42, 'done', 54, 'done']); }); @@ -159,11 +157,11 @@ describe('bindNodeCallback', () => { const results: Array = []; boundCallback() - .subscribe((x: any) => { + .subscribe({ next: (x: any) => { results.push(typeof x); - }, null, () => { + }, complete: () => { results.push('done'); - }); + } }); rxTestScheduler.flush(); @@ -178,11 +176,11 @@ describe('bindNodeCallback', () => { const results: Array = []; boundCallback(42) - .subscribe(x => { + .subscribe({ next: x => { results.push(x); - }, null, () => { + }, complete: () => { results.push('done'); - }); + } }); rxTestScheduler.flush(); @@ -198,9 +196,7 @@ describe('bindNodeCallback', () => { boundCallback.call({datum: 42}) .subscribe( - (x: number) => results.push(x), - null, - () => results.push('done') + { next: (x: number) => results.push(x), complete: () => results.push('done') } ); rxTestScheduler.flush(); @@ -216,13 +212,13 @@ describe('bindNodeCallback', () => { const boundCallback = bindNodeCallback(callback, rxTestScheduler); boundCallback(42) - .subscribe(x => { + .subscribe({ next: x => { throw new Error('should not next'); - }, (err: any) => { + }, error: (err: any) => { expect(err).to.equal(expected); - }, () => { + }, complete: () => { throw new Error('should not complete'); - }); + } }); rxTestScheduler.flush(); }); @@ -238,13 +234,13 @@ describe('bindNodeCallback', () => { const results: Array = []; boundCallback() - .subscribe(() => { + .subscribe({ next: () => { throw new Error('should not next'); - }, (err: any) => { + }, error: (err: any) => { results.push(err); - }, () => { + }, complete: () => { throw new Error('should not complete'); - }); + } }); rxTestScheduler.flush(); @@ -260,11 +256,11 @@ describe('bindNodeCallback', () => { const results: Array = []; boundCallback(42) - .subscribe(x => { + .subscribe({ next: x => { results.push(x); - }, null, () => { + }, complete: () => { results.push('done'); - }); + } }); rxTestScheduler.flush(); @@ -283,17 +279,17 @@ describe('bindNodeCallback', () => { const source = boundCallback(42); - source.subscribe(x => { + source.subscribe({ next: x => { results1.push(x); - }, null, () => { + }, complete: () => { results1.push('done'); - }); + } }); - source.subscribe(x => { + source.subscribe({ next: x => { results2.push(x); - }, null, () => { + }, complete: () => { results2.push('done'); - }); + } }); rxTestScheduler.flush(); @@ -351,11 +347,11 @@ describe('bindNodeCallback', () => { const source = boundCallback(42); - const subscription = source.subscribe((x: any) => { + const subscription = source.subscribe({ next: (x: any) => { results1.push(x); - }, null, () => { + }, complete: () => { results1.push('done'); - }); + } }); subscription.unsubscribe(); diff --git a/spec/observables/combineLatest-spec.ts b/spec/observables/combineLatest-spec.ts index d04f2bd650..93f42af5fb 100644 --- a/spec/observables/combineLatest-spec.ts +++ b/spec/observables/combineLatest-spec.ts @@ -86,16 +86,14 @@ describe('static combineLatest', () => { const actual: [number, number][] = []; //type definition need to be updated combineLatest(a, b, queueScheduler).subscribe( - (vals) => { + { next: (vals) => { actual.push(vals); - }, - () => { + }, error: () => { done(new Error('should not be called')); - }, - () => { + }, complete: () => { expect(actual).to.deep.equal(r); done(); - } + } } ); }); diff --git a/spec/observables/concat-spec.ts b/spec/observables/concat-spec.ts index 613e214192..32715fd9b7 100644 --- a/spec/observables/concat-spec.ts +++ b/spec/observables/concat-spec.ts @@ -394,13 +394,12 @@ describe('static concat', () => { const b = of(4, 5, 6, 7, 8, queueScheduler); const r = [1, 2, 3, 4, 5, 6, 7, 8]; - concat(a, b, queueScheduler).subscribe( - (vals) => { + concat(a, b, queueScheduler).subscribe({ + next: (vals) => { expect(vals).to.equal(r.shift()); }, - null, - done - ); + complete: done, + }); }); it("should use the scheduler even when one Observable is concat'd", (done) => { diff --git a/spec/observables/defer-spec.ts b/spec/observables/defer-spec.ts index f41a81ba77..0574ad62b4 100644 --- a/spec/observables/defer-spec.ts +++ b/spec/observables/defer-spec.ts @@ -55,15 +55,15 @@ describe('defer', () => { }); }); - e1.subscribe( - (x: number) => { + e1.subscribe({ + next: (x: number) => { expect(x).to.equal(expected); done(); }, - (x: any) => { + error: (x: any) => { done(new Error('should not be called')); - } - ); + }, + }); }); it('should accept factory returns promise rejects', (done) => { @@ -74,18 +74,18 @@ describe('defer', () => { }); }); - e1.subscribe( - (x: number) => { + e1.subscribe({ + next: (x: number) => { done(new Error('should not be called')); }, - (x: any) => { + error: (x: any) => { expect(x).to.equal(expected); done(); }, - () => { + complete: () => { done(new Error('should not be called')); - } - ); + }, + }); }); it('should create an observable from error', () => { diff --git a/spec/observables/dom/ajax-spec.ts b/spec/observables/dom/ajax-spec.ts index a3457f2d9a..e6a17a9bf1 100644 --- a/spec/observables/dom/ajax-spec.ts +++ b/spec/observables/dom/ajax-spec.ts @@ -52,7 +52,7 @@ describe('ajax', () => { method: '', }; - ajax(obj).subscribe(null, (err) => expect(err).to.exist); + ajax(obj).subscribe({ error: (err) => expect(err).to.exist }); }); it('should create XMLHttpRequest for CORS', () => { @@ -208,6 +208,33 @@ describe('ajax', () => { }); }); + it('should NOT set the X-Requested-With if crossDomain is true', () => { + ajax({ + url: '/test/monkey', + method: 'GET', + crossDomain: true, + }).subscribe(); + + const request = MockXMLHttpRequest.mostRecent; + + expect(request.requestHeaders).to.not.have.key('x-requested-with'); + }); + + it('should not alter user-provided X-Requested-With header, even if crossDomain is true', () => { + ajax({ + url: '/test/monkey', + method: 'GET', + crossDomain: true, + headers: { + 'x-requested-with': 'Custom-XMLHttpRequest', + }, + }).subscribe(); + + const request = MockXMLHttpRequest.mostRecent; + + expect(request.requestHeaders['x-requested-with']).to.equal('Custom-XMLHttpRequest'); + }); + it('should not set default Content-Type header when no body is sent', () => { const obj: AjaxConfig = { url: '/talk-to-me-goose', @@ -231,17 +258,17 @@ describe('ajax', () => { createXHR: () => { throw new Error('wokka wokka'); }, - }).subscribe( - () => { + }).subscribe({ + next: () => { throw new Error('should not next'); }, - (err: any) => { + error: (err: any) => { error = err; }, - () => { + complete: () => { throw new Error('should not complete'); - } - ); + }, + }); expect(error).to.be.an('error', 'wokka wokka'); }); @@ -260,18 +287,18 @@ describe('ajax', () => { }; return ret as any; }, - }).subscribe( - () => { + }).subscribe({ + next: () => { done(new Error('should not be called')); }, - (e: Error) => { + error: (e: Error) => { expect(e).to.be.equal(expected); done(); }, - () => { + complete: () => { done(new Error('should not be called')); - } - ); + }, + }); }); it('should succeed on 200', () => { @@ -282,15 +309,14 @@ describe('ajax', () => { ajax({ url: '/flibbertyJibbet', method: '', - }).subscribe( - (x: any) => { + }).subscribe({ + next: (x: any) => { result = x; }, - null, - () => { + complete: () => { complete = true; - } - ); + }, + }); expect(MockXMLHttpRequest.mostRecent.url).to.equal('/flibbertyJibbet'); @@ -314,17 +340,17 @@ describe('ajax', () => { // No `response` property on the object (for older IE). MockXMLHttpRequest.noResponseProp = true; - ajax(obj).subscribe( - () => { + ajax(obj).subscribe({ + next: () => { throw new Error('should not next'); }, - (err: any) => { + error: (err: any) => { error = err; }, - () => { + complete: () => { throw new Error('should not complete'); - } - ); + }, + }); MockXMLHttpRequest.mostRecent.respondWith({ status: 207, @@ -343,17 +369,17 @@ describe('ajax', () => { method: '', }; - ajax(obj).subscribe( - () => { + ajax(obj).subscribe({ + next: () => { throw new Error('should not next'); }, - (err: any) => { + error: (err: any) => { error = err; }, - () => { + complete: () => { throw new Error('should not complete'); - } - ); + }, + }); expect(MockXMLHttpRequest.mostRecent.url).to.equal('/flibbertyJibbet'); @@ -377,15 +403,14 @@ describe('ajax', () => { method: '', }; - ajax(obj).subscribe( - (x: any) => { + ajax(obj).subscribe({ + next: (x: any) => { result = x; }, - null, - () => { + complete: () => { complete = true; - } - ); + }, + }); expect(MockXMLHttpRequest.mostRecent.url).to.equal('/flibbertyJibbet'); @@ -407,17 +432,17 @@ describe('ajax', () => { method: '', }; - ajax(obj).subscribe( - () => { + ajax(obj).subscribe({ + next: () => { throw new Error('should not next'); }, - (err: any) => { + error: (err: any) => { error = err; }, - () => { + complete: () => { throw new Error('should not complete'); - } - ); + }, + }); MockXMLHttpRequest.mostRecent.respondWith({ status: 404, @@ -434,16 +459,16 @@ describe('ajax', () => { it('should succeed no settings', () => { const expected = JSON.stringify({ foo: 'bar' }); - ajax('/flibbertyJibbet').subscribe( - (x: any) => { + ajax('/flibbertyJibbet').subscribe({ + next: (x: any) => { expect(x.status).to.equal(200); expect(x.xhr.method).to.equal('GET'); expect(x.xhr.responseText).to.equal(expected); }, - () => { + error: () => { throw 'should not have been called'; - } - ); + }, + }); expect(MockXMLHttpRequest.mostRecent.url).to.equal('/flibbertyJibbet'); MockXMLHttpRequest.mostRecent.respondWith({ @@ -455,19 +480,19 @@ describe('ajax', () => { it('should fail no settings', () => { const expected = JSON.stringify({ foo: 'bar' }); - ajax('/flibbertyJibbet').subscribe( - () => { + ajax('/flibbertyJibbet').subscribe({ + next: () => { throw 'should not have been called'; }, - (x: any) => { + error: (x: any) => { expect(x.status).to.equal(500); expect(x.xhr.method).to.equal('GET'); expect(x.xhr.responseText).to.equal(expected); }, - () => { + complete: () => { throw 'should not have been called'; - } - ); + }, + }); expect(MockXMLHttpRequest.mostRecent.url).to.equal('/flibbertyJibbet'); MockXMLHttpRequest.mostRecent.respondWith({ @@ -483,18 +508,18 @@ describe('ajax', () => { timeout: 10, }; - ajax(obj).subscribe( - (x: any) => { + ajax(obj).subscribe({ + next: (x: any) => { expect(x.status).to.equal(200); expect(x.xhr.method).to.equal('GET'); expect(x.xhr.async).to.equal(true); expect(x.xhr.timeout).to.equal(10); expect(x.xhr.responseType).to.equal('text'); }, - () => { + error: () => { throw 'should not have been called'; - } - ); + }, + }); const request = MockXMLHttpRequest.mostRecent; @@ -515,18 +540,18 @@ describe('ajax', () => { timeout: 10, }; - ajax(obj).subscribe( - () => { + ajax(obj).subscribe({ + next: () => { throw 'should not have been called'; }, - (e) => { + error: (e) => { expect(e.status).to.equal(0); expect(e.xhr.method).to.equal('GET'); expect(e.xhr.async).to.equal(true); expect(e.xhr.timeout).to.equal(10); expect(e.xhr.responseType).to.equal('text'); - } - ); + }, + }); const request = MockXMLHttpRequest.mostRecent; @@ -664,18 +689,18 @@ describe('ajax', () => { }, }; - ajax(obj).subscribe( - () => { + ajax(obj).subscribe({ + next: () => { done(new Error('should not be called')); }, - (e: Error) => { + error: (e: Error) => { expect(e).to.be.equal(expected); done(); }, - () => { + complete: () => { done(new Error('should not be called')); - } - ); + }, + }); }); }); @@ -685,15 +710,14 @@ describe('ajax', () => { let result; let complete = false; - ajax.get('/flibbertyJibbet').subscribe( - (x) => { + ajax.get('/flibbertyJibbet').subscribe({ + next: (x) => { result = x.response; }, - null, - () => { + complete: () => { complete = true; - } - ); + }, + }); const request = MockXMLHttpRequest.mostRecent; @@ -712,15 +736,14 @@ describe('ajax', () => { let result; let complete = false; - ajax.get('/flibbertyJibbet').subscribe( - (x) => { + ajax.get('/flibbertyJibbet').subscribe({ + next: (x) => { result = x.response; }, - null, - () => { + complete: () => { complete = true; - } - ); + }, + }); const request = MockXMLHttpRequest.mostRecent; @@ -743,15 +766,14 @@ describe('ajax', () => { let result; let complete = false; - ajax.getJSON('/flibbertyJibbet').subscribe( - (x) => { + ajax.getJSON('/flibbertyJibbet').subscribe({ + next: (x) => { result = x; }, - null, - () => { + complete: () => { complete = true; - } - ); + }, + }); const request = MockXMLHttpRequest.mostRecent; @@ -773,15 +795,14 @@ describe('ajax', () => { let result: AjaxResponse; let complete = false; - ajax.post('/flibbertyJibbet', expected).subscribe( - (x) => { + ajax.post('/flibbertyJibbet', expected).subscribe({ + next: (x) => { result = x; }, - null, - () => { + complete: () => { complete = true; - } - ); + }, + }); const request = MockXMLHttpRequest.mostRecent; @@ -806,15 +827,14 @@ describe('ajax', () => { let result: AjaxResponse; let complete = false; - ajax.post('/flibbertyJibbet', undefined).subscribe( - (x) => { + ajax.post('/flibbertyJibbet', undefined).subscribe({ + next: (x) => { result = x; }, - null, - () => { + complete: () => { complete = true; - } - ); + }, + }); const request = MockXMLHttpRequest.mostRecent; @@ -897,15 +917,14 @@ describe('ajax', () => { let result: AjaxResponse; let complete = false; - ajax.patch('/flibbertyJibbet', expected).subscribe( - (x) => { + ajax.patch('/flibbertyJibbet', expected).subscribe({ + next: (x) => { result = x; }, - null, - () => { + complete: () => { complete = true; - } - ); + }, + }); const request = MockXMLHttpRequest.mostRecent; @@ -1025,7 +1044,7 @@ describe('ajax', () => { const request = { async: true, body: undefined, - crossDomain: true, + crossDomain: false, headers: { 'x-requested-with': 'XMLHttpRequest', }, @@ -1153,7 +1172,7 @@ describe('ajax', () => { const request = { async: true, body: undefined, - crossDomain: true, + crossDomain: false, headers: { 'x-requested-with': 'XMLHttpRequest', }, diff --git a/spec/observables/dom/webSocket-spec.ts b/spec/observables/dom/webSocket-spec.ts index fbebdb4c69..a121e3f0e2 100644 --- a/spec/observables/dom/webSocket-spec.ts +++ b/spec/observables/dom/webSocket-spec.ts @@ -403,11 +403,11 @@ describe('webSocket', () => { } }); - subject.subscribe((x: any) => { + subject.subscribe({ next: (x: any) => { expect(x).to.equal('this should not happen'); - }, (err: any) => { + }, error: (err: any) => { expect(err).to.be.an('error', 'I am a bad error'); - }); + } }); const socket = MockWebSocket.lastSocket; socket.open(); @@ -468,9 +468,9 @@ describe('webSocket', () => { socket.triggerClose(expected[0]); expect(closes.length).to.equal(1); - subject.subscribe(null, function (err) { + subject.subscribe({ error: function (err) { expect(err).to.equal(expected[1]); - }); + } }); socket = MockWebSocket.lastSocket; socket.open(); @@ -492,11 +492,11 @@ describe('webSocket', () => { } }); - subject.subscribe((x: any) => { + subject.subscribe({ next: (x: any) => { expect(x).to.equal('this should not happen'); - }, (err: any) => { + }, error: (err: any) => { expect(err).to.be.an('error', 'connection refused'); - }); + } }); subject.unsubscribe(); }); @@ -640,9 +640,7 @@ describe('webSocket', () => { takeWhile((req: any) => !req.complete) ) .subscribe( - () => results.push('A next'), - (e) => results.push('A error ' + e), - () => results.push('A complete') + { next: () => results.push('A next'), error: (e) => results.push('A error ' + e), complete: () => results.push('A complete') } ); socketSubject.multiplex( @@ -650,9 +648,7 @@ describe('webSocket', () => { () => results.push('B unsub'), (req: any) => req.id === 'B') .subscribe( - () => results.push('B next'), - (e) => results.push('B error ' + e), - () => results.push('B complete') + { next: () => results.push('B next'), error: (e) => results.push('B error ' + e), complete: () => results.push('B complete') } ); // Setup socket and send messages @@ -696,9 +692,7 @@ describe('webSocket', () => { ).pipe( takeWhile(req => !req.complete) ).subscribe( - () => results.push('A next'), - (e) => results.push('A error ' + e), - () => results.push('A complete') + { next: () => results.push('A next'), error: (e) => results.push('A error ' + e), complete: () => results.push('A complete') } ); socketSubject.multiplex( @@ -708,9 +702,7 @@ describe('webSocket', () => { ).pipe( takeWhile(req => !req.complete) ).subscribe( - () => results.push('B next'), - (e) => results.push('B error ' + e), - () => results.push('B complete') + { next: () => results.push('B next'), error: (e) => results.push('B error ' + e), complete: () => results.push('B complete') } ); // Setup socket and send messages diff --git a/spec/observables/from-promise-spec.ts b/spec/observables/from-promise-spec.ts index 7c1c436760..f94f644695 100644 --- a/spec/observables/from-promise-spec.ts +++ b/spec/observables/from-promise-spec.ts @@ -10,26 +10,24 @@ describe('from (fromPromise)', () => { const promise = Promise.resolve(42); from(promise) .subscribe( - (x) => { expect(x).to.equal(42); }, - (x) => { + { next: (x) => { expect(x).to.equal(42); }, error: (x) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { done(); - }); + } }); }); it('should raise error from a rejected promise', (done) => { const promise = Promise.reject('bad'); from(promise) - .subscribe((x) => { + .subscribe({ next: (x) => { done(new Error('should not be called')); - }, - (e) => { + }, error: (e) => { expect(e).to.equal('bad'); done(); - }, () => { + }, complete: () => { done(new Error('should not be called')); - }); + } }); }); it('should share the underlying promise with multiple subscribers', (done) => { @@ -38,19 +36,17 @@ describe('from (fromPromise)', () => { observable .subscribe( - (x) => { expect(x).to.equal(42); }, - (x) => { + { next: (x) => { expect(x).to.equal(42); }, error: (x) => { done(new Error('should not be called')); - }, undefined); + } }); setTimeout(() => { observable .subscribe( - (x) => { expect(x).to.equal(42); }, - (x) => { + { next: (x) => { expect(x).to.equal(42); }, error: (x) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { done(); - }); + } }); }); }); @@ -60,12 +56,11 @@ describe('from (fromPromise)', () => { expect(x).to.equal(42); from(promise) .subscribe( - (y) => { expect(y).to.equal(42); }, - (x) => { + { next: (y) => { expect(y).to.equal(42); }, error: (x) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { done(); - }); + } }); }, () => { done(new Error('should not be called')); }); @@ -84,37 +79,34 @@ describe('from (fromPromise)', () => { const promise = new CustomPromise(Promise.resolve(42)); from(promise) .subscribe( - (x) => { expect(x).to.equal(42); }, - () => { + { next: (x) => { expect(x).to.equal(42); }, error: () => { done(new Error('should not be called')); - }, () => { + }, complete: () => { done(); - }); + } }); }); it('should emit a value from a resolved promise on a separate scheduler', (done) => { const promise = Promise.resolve(42); from(promise, asapScheduler) .subscribe( - (x) => { expect(x).to.equal(42); }, - (x) => { + { next: (x) => { expect(x).to.equal(42); }, error: (x) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { done(); - }); + } }); }); it('should raise error from a rejected promise on a separate scheduler', (done) => { const promise = Promise.reject('bad'); from(promise, asapScheduler) .subscribe( - (x) => { done(new Error('should not be called')); }, - (e) => { + { next: (x) => { done(new Error('should not be called')); }, error: (e) => { expect(e).to.equal('bad'); done(); - }, () => { + }, complete: () => { done(new Error('should not be called')); - }); + } }); }); it('should share the underlying promise with multiple subscribers on a separate scheduler', (done) => { @@ -123,20 +115,17 @@ describe('from (fromPromise)', () => { observable .subscribe( - (x) => { expect(x).to.equal(42); }, - (x) => { + { next: (x) => { expect(x).to.equal(42); }, error: (x) => { done(new Error('should not be called')); - }, - undefined); + } }); setTimeout(() => { observable .subscribe( - (x) => { expect(x).to.equal(42); }, - (x) => { + { next: (x) => { expect(x).to.equal(42); }, error: (x) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { done(); - }); + } }); }); }); @@ -146,7 +135,7 @@ describe('from (fromPromise)', () => { const completeSpy = sinon.spy(); const promise = Promise.resolve(42); const subscription = from(promise) - .subscribe(nextSpy, throwSpy, completeSpy); + .subscribe({ next: nextSpy, error: throwSpy, complete: completeSpy }); subscription.unsubscribe(); setTimeout(() => { diff --git a/spec/observables/from-spec.ts b/spec/observables/from-spec.ts index 1b5fc7fa32..18c1f67b2d 100644 --- a/spec/observables/from-spec.ts +++ b/spec/observables/from-spec.ts @@ -257,34 +257,30 @@ describe('from', () => { let nextInvoked = false; from(source.createValue()) .subscribe( - (x) => { + { next: (x) => { nextInvoked = true; expect(x).to.equal('x'); - }, - (x) => { + }, error: (x) => { done(new Error('should not be called')); - }, - () => { + }, complete: () => { expect(nextInvoked).to.equal(true); done(); - } + } } ); }); it(`should accept ${source.name} and scheduler`, (done) => { let nextInvoked = false; from(source.createValue(), asyncScheduler) .subscribe( - (x) => { + { next: (x) => { nextInvoked = true; expect(x).to.equal('x'); - }, - (x) => { + }, error: (x) => { done(new Error('should not be called')); - }, - () => { + }, complete: () => { expect(nextInvoked).to.equal(true); done(); - } + } } ); expect(nextInvoked).to.equal(false); }); @@ -296,17 +292,15 @@ describe('from', () => { let nextInvoked = false; from((handler as any)).pipe(first()).subscribe( - (x) => { + { next: (x) => { nextInvoked = true; expect(x).to.equal('x'); - }, - (x) => { + }, error: (x) => { done(new Error('should not be called')); - }, - () => { + }, complete: () => { expect(nextInvoked).to.equal(true); done(); - } + } } ); handler('x'); }); diff --git a/spec/observables/fromEvent-spec.ts b/spec/observables/fromEvent-spec.ts index 9fe29b1b64..a02f6331b4 100644 --- a/spec/observables/fromEvent-spec.ts +++ b/spec/observables/fromEvent-spec.ts @@ -229,13 +229,13 @@ describe('fromEvent', () => { }; fromEvent(obj, 'click').pipe(take(1)) - .subscribe((e: any) => { + .subscribe({ next: (e: any) => { expect(e).to.equal('test'); - }, (err: any) => { + }, error: (err: any) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { done(); - }); + } }); send('test'); }); @@ -256,13 +256,13 @@ describe('fromEvent', () => { } fromEvent(obj, 'click', selector).pipe(take(1)) - .subscribe((e: any) => { + .subscribe({ next: (e: any) => { expect(e).to.equal('test!'); - }, (err: any) => { + }, error: (err: any) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { done(); - }); + } }); send('test'); }); @@ -283,13 +283,13 @@ describe('fromEvent', () => { } fromEvent(obj, 'click', selector).pipe(take(1)) - .subscribe((e: any) => { + .subscribe({ next: (e: any) => { expect(e).not.exist; - }, (err: any) => { + }, error: (err: any) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { done(); - }); + } }); send(); }); @@ -310,13 +310,13 @@ describe('fromEvent', () => { } fromEvent(obj, 'click', selector).pipe(take(1)) - .subscribe((e: any) => { + .subscribe({ next: (e: any) => { expect(e).to.equal('no arguments'); - }, (err: any) => { + }, error: (err: any) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { done(); - }); + } }); send(); }); @@ -337,13 +337,13 @@ describe('fromEvent', () => { } fromEvent(obj, 'click', selector).pipe(take(1)) - .subscribe((e: any) => { + .subscribe({ next: (e: any) => { expect(e).to.deep.equal([1, 2, 3]); - }, (err: any) => { + }, error: (err: any) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { done(); - }); + } }); send(1, 2, 3); }); @@ -360,13 +360,13 @@ describe('fromEvent', () => { }; fromEvent(obj, 'click').pipe(take(1)) - .subscribe((e: any) => { + .subscribe({ next: (e: any) => { expect(e).to.deep.equal([1, 2, 3]); - }, (err: any) => { + }, error: (err: any) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { done(); - }); + } }); send(1, 2, 3); }); diff --git a/spec/observables/fromEventPattern-spec.ts b/spec/observables/fromEventPattern-spec.ts index 66547f9fcb..92e19c6d76 100644 --- a/spec/observables/fromEventPattern-spec.ts +++ b/spec/observables/fromEventPattern-spec.ts @@ -63,11 +63,10 @@ describe('fromEventPattern', () => { fromEventPattern((h: any) => { throw 'bad'; }, noop).subscribe( - () => done(new Error('should not be called')), - (err: any) => { + { next: () => done(new Error('should not be called')), error: (err: any) => { expect(err).to.equal('bad'); done(); - }, () => done(new Error('should not be called'))); + }, complete: () => done(new Error('should not be called')) }); }); it('should accept a selector that maps outgoing values', (done) => { @@ -89,13 +88,13 @@ describe('fromEventPattern', () => { }; fromEventPattern(addHandler, removeHandler, selector).pipe(take(1)) - .subscribe((x: any) => { + .subscribe({ next: (x: any) => { expect(x).to.equal('testme!'); - }, (err: any) => { + }, error: (err: any) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { done(); - }); + } }); trigger('test', 'me'); }); @@ -119,14 +118,14 @@ describe('fromEventPattern', () => { }; fromEventPattern(addHandler, removeHandler, selector) - .subscribe((x: any) => { + .subscribe({ next: (x: any) => { done(new Error('should not be called')); - }, (err: any) => { + }, error: (err: any) => { expect(err).to.equal('bad'); done(); - }, () => { + }, complete: () => { done(new Error('should not be called')); - }); + } }); trigger('test'); }); diff --git a/spec/observables/if-spec.ts b/spec/observables/if-spec.ts index 85a2b6eeda..e59cc1a2ad 100644 --- a/spec/observables/if-spec.ts +++ b/spec/observables/if-spec.ts @@ -38,13 +38,13 @@ describe('iif', () => { const expected = 42; const e1 = iif(() => true, new Promise((resolve: any) => { resolve(expected); }), of()); - e1.subscribe(x => { + e1.subscribe({ next: x => { expect(x).to.equal(expected); - }, (x) => { + }, error: (x) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { done(); - }); + } }); }); it('should accept resolved promise as elseSource', (done) => { @@ -53,13 +53,13 @@ describe('iif', () => { of('a'), new Promise((resolve: any) => { resolve(expected); })); - e1.subscribe(x => { + e1.subscribe({ next: x => { expect(x).to.equal(expected); - }, (x) => { + }, error: (x) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { done(); - }); + } }); }); it('should accept rejected promise as elseSource', (done) => { @@ -68,27 +68,27 @@ describe('iif', () => { of('a'), new Promise((resolve: any, reject: any) => { reject(expected); })); - e1.subscribe(x => { + e1.subscribe({ next: x => { done(new Error('should not be called')); - }, (x) => { + }, error: (x) => { expect(x).to.equal(expected); done(); - }, () => { + }, complete: () => { done(new Error('should not be called')); - }); + } }); }); it('should accept rejected promise as thenSource', (done) => { const expected = 42; const e1 = iif(() => true, new Promise((resolve: any, reject: any) => { reject(expected); }), of()); - e1.subscribe(x => { + e1.subscribe({ next: x => { done(new Error('should not be called')); - }, (x) => { + }, error: (x) => { expect(x).to.equal(expected); done(); - }, () => { + }, complete: () => { done(new Error('should not be called')); - }); + } }); }); }); diff --git a/spec/observables/interval-spec.ts b/spec/observables/interval-spec.ts index 01840fecbc..bb9d2dd3c9 100644 --- a/spec/observables/interval-spec.ts +++ b/spec/observables/interval-spec.ts @@ -47,18 +47,18 @@ describe('interval', () => { const values: number[] = []; const expected = [0, 1, 2, 3, 4, 5, 6]; const e1 = interval(5); - const subscription = e1.subscribe((x: number) => { + const subscription = e1.subscribe({ next: (x: number) => { values.push(x); if (x === 6) { subscription.unsubscribe(); expect(values).to.deep.equal(expected); done(); } - }, (err: any) => { + }, error: (err: any) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { done(new Error('should not be called')); - }); + } }); }); it('should create an observable emitting periodically with the AsapScheduler', (done) => { diff --git a/spec/observables/of-spec.ts b/spec/observables/of-spec.ts index 5072cc4345..3f4b9e9b03 100644 --- a/spec/observables/of-spec.ts +++ b/spec/observables/of-spec.ts @@ -23,26 +23,26 @@ describe('of', () => { let i = 0; of(1, 'a', x) - .subscribe((y: any) => { + .subscribe({ next: (y: any) => { expect(y).to.equal(expected[i++]); - }, (x) => { + }, error: (x) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { done(); - }); + } }); }); it('should emit one value', (done) => { let calls = 0; - of(42).subscribe((x: number) => { + of(42).subscribe({ next: (x: number) => { expect(++calls).to.equal(1); expect(x).to.equal(42); - }, (err: any) => { + }, error: (err: any) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { done(); - }); + } }); }); it('should handle an Observable as the only value', () => { diff --git a/spec/observables/pairs-spec.ts b/spec/observables/pairs-spec.ts index 0ae722a547..a5bc342282 100644 --- a/spec/observables/pairs-spec.ts +++ b/spec/observables/pairs-spec.ts @@ -24,14 +24,14 @@ describe('pairs', () => { ['c', 3] ]; - pairs({a: 1, b: 2, c: 3}).subscribe(x => { + pairs({a: 1, b: 2, c: 3}).subscribe({ next: x => { expect(x).to.deep.equal(expected.shift()); - }, x => { + }, error: x => { done(new Error('should not be called')); - }, () => { + }, complete: () => { expect(expected).to.be.empty; done(); - }); + } }); }); it('should work with empty object', () => { diff --git a/spec/observables/race-spec.ts b/spec/observables/race-spec.ts index 32fdedf962..6d6e43e676 100644 --- a/spec/observables/race-spec.ts +++ b/spec/observables/race-spec.ts @@ -208,8 +208,8 @@ describe('static race', () => { it('should support a single ObservableInput argument', (done) => { const source = race(Promise.resolve(42)); - source.subscribe(value => { + source.subscribe({ next: value => { expect(value).to.equal(42); - }, done, done); + }, error: done, complete: done }); }); }); diff --git a/spec/observables/range-spec.ts b/spec/observables/range-spec.ts index 478e580bca..d3a9fee832 100644 --- a/spec/observables/range-spec.ts +++ b/spec/observables/range-spec.ts @@ -58,16 +58,16 @@ describe('range', () => { const source = range(12, 4, asap); - source.subscribe(function (x) { + source.subscribe({ next: function (x) { expect(asap.schedule).have.been.called; const exp = expected.shift(); expect(x).to.equal(exp); - }, function (x) { + }, error: function (x) { done(new Error('should not be called')); - }, () => { + }, complete: () => { (asap.schedule).restore(); done(); - }); + } }); }); diff --git a/spec/observables/throwError-spec.ts b/spec/observables/throwError-spec.ts index 5e84d9b0e0..8a590bf0da 100644 --- a/spec/observables/throwError-spec.ts +++ b/spec/observables/throwError-spec.ts @@ -22,16 +22,16 @@ describe('throwError', () => { it('should emit one value', (done) => { let calls = 0; - throwError(() => 'bad').subscribe( - () => { + throwError(() => 'bad').subscribe({ + next: () => { done(new Error('should not be called')); }, - (err) => { + error: (err) => { expect(++calls).to.equal(1); expect(err).to.equal('bad'); done(); - } - ); + }, + }); }); it('should accept scheduler', () => { diff --git a/spec/observables/using-spec.ts b/spec/observables/using-spec.ts index 9daae72487..9126d60746 100644 --- a/spec/observables/using-spec.ts +++ b/spec/observables/using-spec.ts @@ -28,13 +28,13 @@ describe('using', () => { () => new Subscription(() => disposed = true), (resource) => new Promise((resolve: any) => { resolve(expected); })); - e1.subscribe(x => { + e1.subscribe({ next: x => { expect(x).to.equal(expected); - }, (x) => { + }, error: (x) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { done(); - }); + } }); }); it('should accept factory returns promise rejects', (done) => { @@ -45,14 +45,14 @@ describe('using', () => { () => new Subscription(() => disposed = true), (resource) => new Promise((resolve: any, reject: any) => { reject(expected); })); - e1.subscribe(x => { + e1.subscribe({ next: x => { done(new Error('should not be called')); - }, (x) => { + }, error: (x) => { expect(x).to.equal(expected); done(); - }, () => { + }, complete: () => { done(new Error('should not be called')); - }); + } }); }); it('should raise error when resource factory throws', (done) => { @@ -68,14 +68,14 @@ describe('using', () => { } ); - source.subscribe((x) => { + source.subscribe({ next: (x) => { done(new Error('should not be called')); - }, (x) => { + }, error: (x) => { expect(x).to.equal(expectedError); done(); - }, () => { + }, complete: () => { done(new Error('should not be called')); - }); + } }); }); it('should raise error when observable factory throws', (done) => { @@ -89,13 +89,13 @@ describe('using', () => { } ); - source.subscribe((x) => { + source.subscribe({ next: (x) => { done(new Error('should not be called')); - }, (x) => { + }, error: (x) => { expect(x).to.equal(error); done(); - }, () => { + }, complete: () => { done(new Error('should not be called')); - }); + } }); }); }); diff --git a/spec/observables/zip-spec.ts b/spec/observables/zip-spec.ts index 6ad750b4d5..60b270ae9a 100644 --- a/spec/observables/zip-spec.ts +++ b/spec/observables/zip-spec.ts @@ -26,9 +26,9 @@ describe('static zip', () => { zip( from(['a', 'b', 'c']), from([1, 2, 3]), (a: string, b: number) => a + b) - .subscribe((x: string) => { + .subscribe({ next: (x: string) => { expect(x).to.equal(expected[i++]); - }, null, done); + }, complete: done }); }); it('should end once one observable completes and its buffer is empty', () => { @@ -524,9 +524,9 @@ describe('static zip', () => { const r = [[1, 4], [2, 5], [3, 6]]; let i = 0; - zip(a, b).subscribe((vals: Array) => { + zip(a, b).subscribe({ next: (vals: Array) => { expect(vals).to.deep.equal(r[i++]); - }, null, done); + }, complete: done }); }); it('should be able to zip all iterables', () => { diff --git a/spec/operators/audit-spec.ts b/spec/operators/audit-spec.ts index 24520c01ef..a1478af602 100644 --- a/spec/operators/audit-spec.ts +++ b/spec/operators/audit-spec.ts @@ -398,15 +398,13 @@ describe('audit operator', () => { e1.pipe( audit(() => Promise.resolve(42)) ).subscribe( - (x: number) => { - expect(x).to.equal(expected.shift()); }, - () => { + { next: (x: number) => { + expect(x).to.equal(expected.shift()); }, error: () => { done(new Error('should not be called')); - }, - () => { + }, complete: () => { expect(expected.length).to.equal(0); done(); - } + } } ); }); @@ -424,16 +422,14 @@ describe('audit operator', () => { } }) ).subscribe( - (x: number) => { - expect(x).to.equal(expected.shift()); }, - (err: any) => { + { next: (x: number) => { + expect(x).to.equal(expected.shift()); }, error: (err: any) => { expect(err).to.be.an('error', 'error'); expect(expected.length).to.equal(0); done(); - }, - () => { + }, complete: () => { done(new Error('should not be called')); - } + } } ); }); diff --git a/spec/operators/bufferToggle-spec.ts b/spec/operators/bufferToggle-spec.ts index da84e4e30c..6a5e3299c4 100644 --- a/spec/operators/bufferToggle-spec.ts +++ b/spec/operators/bufferToggle-spec.ts @@ -430,14 +430,14 @@ describe('bufferToggle operator', () => { bufferToggle(new Promise((resolve: any) => { resolve(42); }), () => { return timer(50); }) - ).subscribe((x) => { + ).subscribe({ next: (x) => { expect(x).to.deep.equal(expected.shift()); - }, (x) => { + }, error: (x) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { expect(expected.length).to.be.equal(0); done(); - }); + } }); }); it('should accept openings rejected promise', (done) => { @@ -453,14 +453,14 @@ describe('bufferToggle operator', () => { bufferToggle(new Promise((resolve: any, reject: any) => { reject(expected); }), () => { return timer(50); }) - ).subscribe((x) => { + ).subscribe({ next: (x) => { done(new Error('should not be called')); - }, (x) => { + }, error: (x) => { expect(x).to.equal(expected); done(); - }, () => { + }, complete: () => { done(new Error('should not be called')); - }); + } }); }); it('should accept closing selector that returns a resolved promise', (done) => { @@ -472,14 +472,14 @@ describe('bufferToggle operator', () => { const expected = [[1]]; e1.pipe(bufferToggle(of(10), () => new Promise((resolve: any) => { resolve(42); }))) - .subscribe((x) => { + .subscribe({ next: (x) => { expect(x).to.deep.equal(expected.shift()); - }, () => { + }, error: () => { done(new Error('should not be called')); - }, () => { + }, complete: () => { expect(expected.length).to.be.equal(0); done(); - }); + } }); }); it('should accept closing selector that returns a rejected promise', (done) => { @@ -492,14 +492,14 @@ describe('bufferToggle operator', () => { const expected = 42; e1.pipe(bufferToggle(of(10), () => new Promise((resolve: any, reject: any) => { reject(expected); }))) - .subscribe((x) => { + .subscribe({ next: (x) => { done(new Error('should not be called')); - }, (x) => { + }, error: (x) => { expect(x).to.equal(expected); done(); - }, () => { + }, complete: () => { done(new Error('should not be called')); - }); + } }); }); it('should handle empty closing observable', () => { diff --git a/spec/operators/bufferWhen-spec.ts b/spec/operators/bufferWhen-spec.ts index 0bda9e0b3e..5d7970cd88 100644 --- a/spec/operators/bufferWhen-spec.ts +++ b/spec/operators/bufferWhen-spec.ts @@ -369,14 +369,14 @@ describe('bufferWhen operator', () => { source.pipe( bufferWhen(() => closing), takeWhile((val: any, index: number) => index < TOO_MANY_INVOCATIONS) - ).subscribe((val: any) => { + ).subscribe({ next: (val: any) => { expect(Array.isArray(val)).to.be.true; expect(val.length).to.equal(0); - }, (err: any) => { + }, error: (err: any) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { done(); - }); + } }); }); it('should handle inner throw', () => { diff --git a/spec/operators/catchError-spec.ts b/spec/operators/catchError-spec.ts index 3646ee0ec9..3bedd1c3c0 100644 --- a/spec/operators/catchError-spec.ts +++ b/spec/operators/catchError-spec.ts @@ -344,13 +344,13 @@ describe('catchError operator', () => { expect(err).to.equal('bad'); return EMPTY; }) - ).subscribe(() => { + ).subscribe({ next: () => { //noop - }, (err: any) => { + }, error: (err: any) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { done(); - }); + } }); }); it('should accept selector returns any ObservableInput', (done) => { @@ -360,13 +360,13 @@ describe('catchError operator', () => { mergeMap(input => throwError(() => ('bad')).pipe(catchError(err => input)) ) - ).subscribe(x => { + ).subscribe({ next: x => { expect(x).to.be.equal(42); - }, (err: any) => { + }, error: (err: any) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { done(); - }); + } }); }); it('should catch errors throw from within the constructor', () => { @@ -412,7 +412,7 @@ describe('catchError operator', () => { catchError(err => throwError(() => (thrownError)) ) - ).subscribe(subscribeSpy, errorSpy); + ).subscribe({ next: subscribeSpy, error: errorSpy }); trueSetTimeout(() => { try { @@ -448,12 +448,10 @@ describe('catchError operator', () => { catchError(err => sourceWithDelay) ) .subscribe( - value => values.push(value), - err => done(err), - () => { + { next: value => values.push(value), error: err => done(err), complete: () => { expect(values).to.deep.equal(['delayed']); done(); - } + } } ); }); diff --git a/spec/operators/combineLatestAll-spec.ts b/spec/operators/combineLatestAll-spec.ts index 33e50fa06a..572ee16119 100644 --- a/spec/operators/combineLatestAll-spec.ts +++ b/spec/operators/combineLatestAll-spec.ts @@ -520,12 +520,12 @@ describe('combineLatestAll operator', () => { const a = of(1, 2, 3); const b = of(4, 5, 6, 7, 8); const expected = [[3, 4], [3, 5], [3, 6], [3, 7], [3, 8]]; - of(a, b).pipe(combineLatestAll()).subscribe((vals) => { + of(a, b).pipe(combineLatestAll()).subscribe({ next: (vals) => { expect(vals).to.deep.equal(expected.shift()); - }, null, () => { + }, complete: () => { expect(expected.length).to.equal(0); done(); - }); + } }); }); it('should combine two immediately-scheduled observables', (done) => { @@ -534,11 +534,11 @@ describe('combineLatestAll operator', () => { const r = [[1, 4], [2, 4], [2, 5], [3, 5], [3, 6], [3, 7], [3, 8]]; of(a, b, queueScheduler).pipe(combineLatestAll()) - .subscribe((vals) => { + .subscribe({ next: (vals) => { expect(vals).to.deep.equal(r.shift()); - }, null, () => { + }, complete: () => { expect(r.length).to.equal(0); done(); - }); + } }); }); }); diff --git a/spec/operators/concat-legacy-spec.ts b/spec/operators/concat-legacy-spec.ts index 269e0dc9ce..64384d8e3e 100644 --- a/spec/operators/concat-legacy-spec.ts +++ b/spec/operators/concat-legacy-spec.ts @@ -33,17 +33,15 @@ describe('concat operator', () => { }).pipe(concat(of(2))); s1.subscribe( - x => { + { next: x => { results.push('Next: ' + x); - }, - x => { + }, error: x => { done(new Error('should not be called')); - }, - () => { + }, complete: () => { results.push('Completed'); expect(results).to.deep.equal(['Next: 1', 'Next: 2', 'Completed']); done(); - } + } } ); }); diff --git a/spec/operators/concatAll-spec.ts b/spec/operators/concatAll-spec.ts index 5d80712d14..23e61c9319 100644 --- a/spec/operators/concatAll-spec.ts +++ b/spec/operators/concatAll-spec.ts @@ -45,16 +45,14 @@ describe('concatAll operator', () => { const res: number[] = []; sources.pipe(concatAll()).subscribe( - x => { + { next: x => { res.push(x); - }, - err => { + }, error: err => { done(new Error('should not be called')); - }, - () => { + }, complete: () => { expect(res).to.deep.equal([0, 1, 2, 3]); done(); - } + } } ); }); @@ -112,17 +110,15 @@ describe('concatAll operator', () => { const res: number[] = []; sources.pipe(concatAll()).subscribe( - x => { + { next: x => { res.push(x); - }, - err => { + }, error: err => { expect(res.length).to.equal(1); expect(err).to.equal(1); done(); - }, - () => { + }, complete: () => { done(new Error('should not be called')); - } + } } ); }); diff --git a/spec/operators/concatMap-spec.ts b/spec/operators/concatMap-spec.ts index f4df6f09a3..f250bb294a 100644 --- a/spec/operators/concatMap-spec.ts +++ b/spec/operators/concatMap-spec.ts @@ -775,16 +775,14 @@ describe('Observable.prototype.concatMap', () => { const results: number[] = []; source.pipe(concatMap(project)).subscribe( - x => { + { next: x => { results.push(x); - }, - err => { + }, error: err => { done(new Error('Subscriber error handler not supposed to be called.')); - }, - () => { + }, complete: () => { expect(results).to.deep.equal([42, 42, 42, 42]); done(); - } + } } ); }); @@ -793,16 +791,14 @@ describe('Observable.prototype.concatMap', () => { const project = (value: any) => from(Promise.reject(42)); source.pipe(concatMap(project)).subscribe( - x => { + { next: x => { done(new Error('Subscriber next handler not supposed to be called.')); - }, - err => { + }, error: err => { expect(err).to.deep.equal(42); done(); - }, - () => { + }, complete: () => { done(new Error('Subscriber complete handler not supposed to be called.')); - } + } } ); }); @@ -812,16 +808,14 @@ describe('Observable.prototype.concatMap', () => { const results: number[] = []; source.pipe(concatMap(project)).subscribe( - x => { + { next: x => { results.push(x); - }, - err => { + }, error: err => { done(new Error('Subscriber error handler not supposed to be called.')); - }, - () => { + }, complete: () => { expect(results).to.deep.equal([4, 4, 4, 4]); done(); - } + } } ); }); @@ -830,16 +824,14 @@ describe('Observable.prototype.concatMap', () => { const project = (value: number, index: number) => from(Promise.reject('' + value + '-' + index)); source.pipe(concatMap(project)).subscribe( - x => { + { next: x => { done(new Error('Subscriber next handler not supposed to be called.')); - }, - err => { + }, error: err => { expect(err).to.deep.equal('4-0'); done(); - }, - () => { + }, complete: () => { done(new Error('Subscriber complete handler not supposed to be called.')); - } + } } ); }); diff --git a/spec/operators/concatMapTo-spec.ts b/spec/operators/concatMapTo-spec.ts index ceef289de2..6cbd6d04a3 100644 --- a/spec/operators/concatMapTo-spec.ts +++ b/spec/operators/concatMapTo-spec.ts @@ -384,32 +384,28 @@ describe('concatMapTo', () => { const results: number[] = []; source.pipe(concatMapTo(from(Promise.resolve(42)))).subscribe( - (x) => { + { next: (x) => { results.push(x); - }, - (err) => { + }, error: (err) => { done(new Error('Subscriber error handler not supposed to be called.')); - }, - () => { + }, complete: () => { expect(results).to.deep.equal([42, 42, 42, 42]); done(); - }); + } }); }); it('should map values to constant rejected promises and concatenate', (done) => { const source = from([4, 3, 2, 1]); source.pipe(concatMapTo(from(Promise.reject(42)))).subscribe( - (x) => { + { next: (x) => { done(new Error('Subscriber next handler not supposed to be called.')); - }, - (err) => { + }, error: (err) => { expect(err).to.equal(42); done(); - }, - () => { + }, complete: () => { done(new Error('Subscriber complete handler not supposed to be called.')); - }); + } }); }); it('should stop listening to a synchronous observable when unsubscribed', () => { diff --git a/spec/operators/concatWith-spec.ts b/spec/operators/concatWith-spec.ts index 9d97dfbc94..10035e28cb 100644 --- a/spec/operators/concatWith-spec.ts +++ b/spec/operators/concatWith-spec.ts @@ -34,17 +34,15 @@ describe('concat operator', () => { }).pipe(concatWith(of(2))); s1.subscribe( - x => { + { next: x => { results.push('Next: ' + x); - }, - x => { + }, error: x => { done(new Error('should not be called')); - }, - () => { + }, complete: () => { results.push('Completed'); expect(results).to.deep.equal(['Next: 1', 'Next: 2', 'Completed']); done(); - } + } } ); }); diff --git a/spec/operators/count-spec.ts b/spec/operators/count-spec.ts index 30455959ed..fd6b2517a0 100644 --- a/spec/operators/count-spec.ts +++ b/spec/operators/count-spec.ts @@ -93,49 +93,49 @@ describe('count', () => { it('should count a range() source observable', (done) => { range(1, 10) .pipe(count()) - .subscribe( - (value: number) => { + .subscribe({ + next: (value: number) => { expect(value).to.equal(10); }, - (x) => { + error: (x) => { done(new Error('should not be called')); }, - () => { + complete: () => { done(); - } - ); + }, + }); }); it('should count a range().skip(1) source observable', (done) => { range(1, 10) .pipe(skip(1), count()) - .subscribe( - (value: number) => { + .subscribe({ + next: (value: number) => { expect(value).to.equal(9); }, - (x) => { + error: (x) => { done(new Error('should not be called')); }, - () => { + complete: () => { done(); - } - ); + }, + }); }); it('should count a range().take(1) source observable', (done) => { range(1, 10) .pipe(take(1), count()) - .subscribe( - (value: number) => { + .subscribe({ + next: (value: number) => { expect(value).to.equal(1); }, - (x) => { + error: (x) => { done(new Error('should not be called')); }, - () => { + complete: () => { done(); - } - ); + }, + }); }); it('should work with error', () => { diff --git a/spec/operators/debounce-spec.ts b/spec/operators/debounce-spec.ts index 877e8c3021..8b16b10b1a 100644 --- a/spec/operators/debounce-spec.ts +++ b/spec/operators/debounce-spec.ts @@ -469,18 +469,18 @@ describe('debounce', () => { resolve(42); }); }) - ).subscribe( - (x: number) => { + ).subscribe({ + next: (x: number) => { expect(x).to.equal(expected.shift()); }, - (x) => { + error: (x) => { done(new Error('should not be called')); }, - () => { + complete: () => { expect(expected.length).to.equal(0); done(); - } - ); + }, + }); }); it('should raises error when promise rejects', (done) => { @@ -500,19 +500,19 @@ describe('debounce', () => { }); } }) - ).subscribe( - (x: number) => { + ).subscribe({ + next: (x: number) => { expect(x).to.equal(expected.shift()); }, - (err: any) => { + error: (err: any) => { expect(err).to.be.an('error', 'error'); expect(expected.length).to.equal(0); done(); }, - () => { + complete: () => { done(new Error('should not be called')); - } - ); + }, + }); }); it('should debounce correctly when synchronously reentered', () => { diff --git a/spec/operators/delayWhen-spec.ts b/spec/operators/delayWhen-spec.ts index 9bf58c4c1e..3bee9205fe 100644 --- a/spec/operators/delayWhen-spec.ts +++ b/spec/operators/delayWhen-spec.ts @@ -304,11 +304,7 @@ describe('delayWhen', () => { of(1) .pipe(delayWhen(() => of(2))) - .subscribe( - () => (next = true), - null, - () => (complete = true) - ); + .subscribe({ next: () => (next = true), complete: () => (complete = true) }); expect(next).to.be.true; expect(complete).to.be.true; @@ -333,8 +329,10 @@ describe('delayWhen', () => { expectObservable( result.pipe( - tap(null, null, () => { - expect(indices).to.deep.equal([0, 1, 2]); + tap({ + complete: () => { + expect(indices).to.deep.equal([0, 1, 2]); + }, }) ) ).toBe(expected); diff --git a/spec/operators/exhaustAll-spec.ts b/spec/operators/exhaustAll-spec.ts index e3607fb413..c06e34b2bf 100644 --- a/spec/operators/exhaustAll-spec.ts +++ b/spec/operators/exhaustAll-spec.ts @@ -240,33 +240,32 @@ describe('exhaust', () => { of(Promise.resolve(1), Promise.resolve(2), Promise.resolve(3)) .pipe(exhaustAll()) - .subscribe( - (x) => { + .subscribe({ + next: (x) => { expect(x).to.equal(expected.shift()); }, - null, - () => { + complete: () => { expect(expected.length).to.equal(0); done(); - } - ); + }, + }); }); it('should handle an observable of promises, where one rejects', (done) => { of(Promise.reject(2), Promise.resolve(1)) .pipe(exhaustAll()) - .subscribe( - (x) => { + .subscribe({ + next: (x) => { done(new Error('should not be called')); }, - (err) => { + error: (err) => { expect(err).to.equal(2); done(); }, - () => { + complete: () => { done(new Error('should not be called')); - } - ); + }, + }); }); it('should stop listening to a synchronous observable when unsubscribed', () => { diff --git a/spec/operators/expand-spec.ts b/spec/operators/expand-spec.ts index 29a92e8ca0..b59271cd22 100644 --- a/spec/operators/expand-spec.ts +++ b/spec/operators/expand-spec.ts @@ -393,16 +393,15 @@ describe('expand', () => { return Promise.resolve(x + x); }) ) - .subscribe( - (x) => { + .subscribe({ + next: (x) => { expect(x).to.equal(expected.shift()); }, - null, - () => { + complete: () => { expect(expected.length).to.equal(0); done(); - } - ); + }, + }); }); it('should recursively flatten Arrays', (done) => { @@ -416,16 +415,15 @@ describe('expand', () => { return [x + x]; }) ) - .subscribe( - (x) => { + .subscribe({ + next: (x) => { expect(x).to.equal(expected.shift()); }, - null, - () => { + complete: () => { expect(expected.length).to.equal(0); done(); - } - ); + }, + }); }); it('should recursively flatten lowercase-o observables', (done) => { @@ -448,16 +446,15 @@ describe('expand', () => { of(1) .pipe(expand(project)) - .subscribe( - (x) => { + .subscribe({ + next: (x) => { expect(x).to.equal(expected.shift()); }, - null, - () => { + complete: () => { expect(expected.length).to.equal(0); done(); - } - ); + }, + }); }); it('should work when passing undefined for the optional arguments', () => { @@ -496,7 +493,7 @@ describe('expand', () => { take(10), toArray() ) - .subscribe((actual) => expect(actual).to.deep.equal(expected), done, done); + .subscribe({ next: (actual) => expect(actual).to.deep.equal(expected), error: done, complete: done }); }); it('should work with the AsyncScheduler', (done) => { @@ -507,7 +504,7 @@ describe('expand', () => { take(10), toArray() ) - .subscribe((actual) => expect(actual).to.deep.equal(expected), done, done); + .subscribe({ next: (actual) => expect(actual).to.deep.equal(expected), error: done, complete: done }); }); it('should stop listening to a synchronous observable when unsubscribed', () => { diff --git a/spec/operators/filter-spec.ts b/spec/operators/filter-spec.ts index c2d10f4ea5..dadd7b5e50 100644 --- a/spec/operators/filter-spec.ts +++ b/spec/operators/filter-spec.ts @@ -154,8 +154,10 @@ describe('filter', () => { const result = e1.pipe( filter(predicate), - tap(null, null, () => { - expect(invoked).to.equal(7); + tap({ + complete: () => { + expect(invoked).to.equal(7); + }, }) ); @@ -329,18 +331,18 @@ describe('filter', () => { throw 'bad'; }) ) - .subscribe( - (x: number) => { + .subscribe({ + next: (x: number) => { done(new Error('should not be called')); }, - (err: any) => { + error: (err: any) => { expect(err).to.equal('bad'); done(); }, - () => { + complete: () => { done(new Error('should not be called')); - } - ); + }, + }); }); it('should not break unsubscription chain when unsubscribed explicitly', () => { diff --git a/spec/operators/finalize-spec.ts b/spec/operators/finalize-spec.ts index ee4d1fd6f3..af932fb848 100644 --- a/spec/operators/finalize-spec.ts +++ b/spec/operators/finalize-spec.ts @@ -17,8 +17,10 @@ describe('finalize', () => { done(); }) ) - .subscribe(null, null, () => { - completed = true; + .subscribe({ + complete: () => { + completed = true; + }, }); }); @@ -37,8 +39,10 @@ describe('finalize', () => { done(); }) ) - .subscribe(null, () => { - thrown = true; + .subscribe({ + error: () => { + thrown = true; + }, }); }); diff --git a/spec/operators/groupBy-spec.ts b/spec/operators/groupBy-spec.ts index fcc6d4caad..7387354d37 100644 --- a/spec/operators/groupBy-spec.ts +++ b/spec/operators/groupBy-spec.ts @@ -43,14 +43,14 @@ describe('groupBy operator', () => { of(1, 2, 3).pipe( groupBy((x) => x % 2) - ).subscribe((g: any) => { + ).subscribe({ next: (g: any) => { const expectedGroup = expectedGroups.shift()!; expect(g.key).to.equal(expectedGroup.key); g.subscribe((x: any) => { expect(x).to.deep.equal(expectedGroup.values.shift()); }); - }, null, done); + }, complete: done }); }); it('should group values with an element selector', (done) => { @@ -61,14 +61,14 @@ describe('groupBy operator', () => { of(1, 2, 3).pipe( groupBy((x) => x % 2, (x) => x + '!') - ).subscribe((g: any) => { + ).subscribe({ next: (g: any) => { const expectedGroup = expectedGroups.shift()!; expect(g.key).to.equal(expectedGroup.key); g.subscribe((x: any) => { expect(x).to.deep.equal(expectedGroup.values.shift()); }); - }, null, done); + }, complete: done }); }); it('should group values with a duration selector', () => { @@ -111,14 +111,14 @@ describe('groupBy operator', () => { // Ensure each inner group reaches the destination after the first event // has been next'd to the group delay(5) - ).subscribe((g: any) => { + ).subscribe({ next: (g: any) => { const expectedGroup = expectedGroups.shift()!; expect(g.key).to.equal(expectedGroup.key); g.subscribe((x: any) => { expect(x).to.deep.equal(expectedGroup.values.shift()); }); - }, null, done); + }, complete: done }); }); it('should handle an empty Observable', () => { @@ -666,13 +666,13 @@ describe('groupBy operator', () => { const expected = '----------------------------#'; e1.pipe(groupBy((val: string) => val.toLowerCase().trim())) - .subscribe((group: any) => { + .subscribe({ next: (group: any) => { rxTestScheduler.schedule(() => { expectObservable(group).toBe(expected); }, 260); - }, () => { + }, error: () => { //noop - }); + } }); expectSubscriptions(e1.subscriptions).toBe(subs); }); @@ -1424,18 +1424,18 @@ describe('groupBy operator', () => { ]; result - .subscribe((g: any) => { + .subscribe({ next: (g: any) => { const expectedGroup = expectedGroups.shift()!; expect(g.key).to.equal(expectedGroup.key); g.subscribe((x: any) => { expect(x).to.deep.equal(expectedGroup.values.shift()); }); - }, (x) => { + }, error: (x) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { done(); - }); + } }); }); it('should stop listening to a synchronous observable when unsubscribed', () => { diff --git a/spec/operators/max-spec.ts b/spec/operators/max-spec.ts index 018621d972..c780957114 100644 --- a/spec/operators/max-spec.ts +++ b/spec/operators/max-spec.ts @@ -123,49 +123,49 @@ describe('max', () => { it('should max a range() source observable', (done) => { range(1, 10000) .pipe(max()) - .subscribe( - (value: number) => { + .subscribe({ + next: (value: number) => { expect(value).to.equal(10000); }, - () => { + error: () => { done(new Error('should not be called')); }, - () => { + complete: () => { done(); - } - ); + }, + }); }); it('should max a range().pipe(skip(1)) source observable', (done) => { range(1, 10) .pipe(skip(1), max()) - .subscribe( - (value: number) => { + .subscribe({ + next: (value: number) => { expect(value).to.equal(10); }, - () => { + error: () => { done(new Error('should not be called')); }, - () => { + complete: () => { done(); - } - ); + }, + }); }); it('should max a range().pipe(take(1)) source observable', (done) => { range(1, 10) .pipe(take(1), max()) - .subscribe( - (value: number) => { + .subscribe({ + next: (value: number) => { expect(value).to.equal(1); }, - () => { + error: () => { done(new Error('should not be called')); }, - () => { + complete: () => { done(); - } - ); + }, + }); }); it('should work with error', () => { diff --git a/spec/operators/merge-legacy-spec.ts b/spec/operators/merge-legacy-spec.ts index 59d5fdd978..e072f40708 100644 --- a/spec/operators/merge-legacy-spec.ts +++ b/spec/operators/merge-legacy-spec.ts @@ -9,15 +9,13 @@ describe('merge (legacy)', () => { const r = [1, 2, 4, 3, 5, 6, 7, 8]; a.pipe(merge(b, queueScheduler)).subscribe( - val => { + { next: val => { expect(val).to.equal(r.shift()); - }, - x => { + }, error: x => { done(new Error('should not be called')); - }, - () => { + }, complete: () => { done(); - } + } } ); }); }); diff --git a/spec/operators/mergeAll-spec.ts b/spec/operators/mergeAll-spec.ts index badabe6c75..e658a521d1 100644 --- a/spec/operators/mergeAll-spec.ts +++ b/spec/operators/mergeAll-spec.ts @@ -455,18 +455,18 @@ describe('mergeAll', () => { const expected = ['a', 'b', 'c', 'd']; const res: string[] = []; - e1.pipe(mergeAll()).subscribe( - (x) => { + e1.pipe(mergeAll()).subscribe({ + next: (x) => { res.push(x); }, - () => { + error: () => { done(new Error('should not be called')); }, - () => { + complete: () => { expect(res).to.deep.equal(expected); done(); - } - ); + }, + }); }); it('should raise error when promise rejects', (done) => { @@ -487,19 +487,19 @@ describe('mergeAll', () => { ]); const res: string[] = []; - e1.pipe(mergeAll()).subscribe( - (x) => { + e1.pipe(mergeAll()).subscribe({ + next: (x) => { res.push(x); }, - (err) => { + error: (err) => { expect(res.length).to.equal(1); expect(err).to.equal('error'); done(); }, - () => { + complete: () => { done(new Error('should not be called')); - } - ); + }, + }); }); it('should finalize generators when merged if the subscription ends', () => { @@ -521,11 +521,7 @@ describe('mergeAll', () => { const iterableObservable = from(iterable as any); of(iterableObservable) .pipe(mergeAll(), take(3)) - .subscribe( - (x) => results.push(x), - null, - () => results.push('GOOSE!') - ); + .subscribe({ next: (x) => results.push(x), complete: () => results.push('GOOSE!') }); expect(results).to.deep.equal(['duck', 'duck', 'duck', 'GOOSE!']); expect(iterable.finalized).to.be.true; @@ -538,13 +534,12 @@ describe('mergeAll', () => { of(a, b) .pipe(mergeAll()) - .subscribe( - (val) => { + .subscribe({ + next: (val) => { expect(val).to.equal(r.shift()); }, - null, - done - ); + complete: done, + }); }); it('should merge two immediately-scheduled observables', (done) => { @@ -554,13 +549,12 @@ describe('mergeAll', () => { of(a, b, queueScheduler) .pipe(mergeAll()) - .subscribe( - (val) => { + .subscribe({ + next: (val) => { expect(val).to.equal(r.shift()); }, - null, - done - ); + complete: done, + }); }); it('should stop listening to a synchronous observable when unsubscribed', () => { diff --git a/spec/operators/mergeMap-spec.ts b/spec/operators/mergeMap-spec.ts index 59a039ce58..745fb9d76b 100644 --- a/spec/operators/mergeMap-spec.ts +++ b/spec/operators/mergeMap-spec.ts @@ -137,36 +137,36 @@ describe('mergeMap', () => { const project = () => from(Promise.resolve(42)); const results: number[] = []; - source.pipe(mergeMap(project)).subscribe( - (x) => { + source.pipe(mergeMap(project)).subscribe({ + next: (x) => { results.push(x); }, - (err) => { + error: (err) => { done(new Error('Subscriber error handler not supposed to be called.')); }, - () => { + complete: () => { expect(results).to.deep.equal([42, 42, 42, 42]); done(); - } - ); + }, + }); }); it('should map values to constant rejected promises and merge', (done) => { const source = from([4, 3, 2, 1]); const project = () => from(Promise.reject(42)); - source.pipe(mergeMap(project)).subscribe( - (x) => { + source.pipe(mergeMap(project)).subscribe({ + next: (x) => { done(new Error('Subscriber next handler not supposed to be called.')); }, - (err) => { + error: (err) => { expect(err).to.equal(42); done(); }, - () => { + complete: () => { done(new Error('Subscriber complete handler not supposed to be called.')); - } - ); + }, + }); }); it('should map values to resolved promises and merge', (done) => { @@ -174,36 +174,36 @@ describe('mergeMap', () => { const project = (value: number, index: number) => from(Promise.resolve(value + index)); const results: number[] = []; - source.pipe(mergeMap(project)).subscribe( - (x) => { + source.pipe(mergeMap(project)).subscribe({ + next: (x) => { results.push(x); }, - (err) => { + error: (err) => { done(new Error('Subscriber error handler not supposed to be called.')); }, - () => { + complete: () => { expect(results).to.deep.equal([4, 4, 4, 4]); done(); - } - ); + }, + }); }); it('should map values to rejected promises and merge', (done) => { const source = from([4, 3, 2, 1]); const project = (value: number, index: number) => from(Promise.reject('' + value + '-' + index)); - source.pipe(mergeMap(project)).subscribe( - (x) => { + source.pipe(mergeMap(project)).subscribe({ + next: (x) => { done(new Error('Subscriber next handler not supposed to be called.')); }, - (err) => { + error: (err) => { expect(err).to.equal('4-0'); done(); }, - () => { + complete: () => { done(new Error('Subscriber complete handler not supposed to be called.')); - } - ); + }, + }); }); it('should mergeMap many outer values to many inner values', () => { @@ -869,16 +869,15 @@ describe('mergeMap', () => { const expected = ['1!', '2!', '3!', '4!']; let completed = false; - source.subscribe( - (x) => { + source.subscribe({ + next: (x) => { expect(x).to.equal(expected.shift()); }, - null, - () => { + complete: () => { expect(expected.length).to.equal(0); completed = true; - } - ); + }, + }); expect(completed).to.be.true; }); @@ -889,16 +888,15 @@ describe('mergeMap', () => { const expected = ['1!', '2!', '3!', '4!']; let completed = false; - source.subscribe( - (x) => { + source.subscribe({ + next: (x) => { expect(x).to.equal(expected.shift()); }, - null, - () => { + complete: () => { expect(expected.length).to.equal(0); completed = true; - } - ); + }, + }); expect(completed).to.be.true; }); diff --git a/spec/operators/mergeMapTo-spec.ts b/spec/operators/mergeMapTo-spec.ts index 04d35d79e6..0660148616 100644 --- a/spec/operators/mergeMapTo-spec.ts +++ b/spec/operators/mergeMapTo-spec.ts @@ -110,35 +110,35 @@ describe('mergeMapTo', () => { const source = from([4, 3, 2, 1]); const results: number[] = []; - source.pipe(mergeMapTo(from(Promise.resolve(42)))).subscribe( - (x) => { + source.pipe(mergeMapTo(from(Promise.resolve(42)))).subscribe({ + next: (x) => { results.push(x); }, - () => { + error: () => { done(new Error('Subscriber error handler not supposed to be called.')); }, - () => { + complete: () => { expect(results).to.deep.equal([42, 42, 42, 42]); done(); - } - ); + }, + }); }); it('should map values to constant rejected promises and merge', (done) => { const source = from([4, 3, 2, 1]); - source.pipe(mergeMapTo(from(Promise.reject(42)))).subscribe( - () => { + source.pipe(mergeMapTo(from(Promise.reject(42)))).subscribe({ + next: () => { done(new Error('Subscriber next handler not supposed to be called.')); }, - (err) => { + error: (err) => { expect(err).to.equal(42); done(); }, - () => { + complete: () => { done(new Error('Subscriber complete handler not supposed to be called.')); - } - ); + }, + }); }); it('should mergeMapTo many outer values to many inner values', () => { @@ -422,16 +422,15 @@ describe('mergeMapTo', () => { const expected = ['!', '!', '!', '!']; let completed = false; - source.subscribe( - (x) => { + source.subscribe({ + next: (x) => { expect(x).to.equal(expected.shift()); }, - null, - () => { + complete: () => { expect(expected.length).to.equal(0); completed = true; - } - ); + }, + }); expect(completed).to.be.true; }); @@ -442,16 +441,15 @@ describe('mergeMapTo', () => { const expected = ['!', '!', '!', '!']; let completed = false; - source.subscribe( - (x) => { + source.subscribe({ + next: (x) => { expect(x).to.equal(expected.shift()); }, - null, - () => { + complete: () => { expect(expected.length).to.equal(0); completed = true; - } - ); + }, + }); expect(completed).to.be.true; }); diff --git a/spec/operators/mergeWith-spec.ts b/spec/operators/mergeWith-spec.ts index 43fa203e2e..185e5a2069 100644 --- a/spec/operators/mergeWith-spec.ts +++ b/spec/operators/mergeWith-spec.ts @@ -34,15 +34,13 @@ describe('merge operator', () => { const r = [1, 2, 3, 4, 5, 6, 7, 8]; a.pipe(mergeWith(b)).subscribe( - val => { + { next: val => { expect(val).to.equal(r.shift()); - }, - () => { + }, error: () => { done(new Error('should not be called')); - }, - () => { + }, complete: () => { done(); - } + } } ); }); @@ -314,11 +312,9 @@ describe('mergeAll operator', () => { of(a, b) .pipe(mergeAll()) .subscribe( - val => { + { next: val => { expect(val).to.equal(r.shift()); - }, - null, - done + }, complete: done } ); }); @@ -330,11 +326,9 @@ describe('mergeAll operator', () => { of(a, b, queueScheduler) .pipe(mergeAll()) .subscribe( - val => { + { next: val => { expect(val).to.equal(r.shift()); - }, - null, - done + }, complete: done } ); }); diff --git a/spec/operators/multicast-spec.ts b/spec/operators/multicast-spec.ts index f88213f1cf..8f78aaa148 100644 --- a/spec/operators/multicast-spec.ts +++ b/spec/operators/multicast-spec.ts @@ -33,17 +33,17 @@ describe('multicast', () => { const connectable = of(1, 2, 3, 4).pipe(multicast(new Subject())) as ConnectableObservable; - connectable.subscribe( - (x) => { + connectable.subscribe({ + next: (x) => { expect(x).to.equal(expected.shift()); }, - () => { + error: () => { done(new Error('should not be called')); }, - () => { + complete: () => { done(); - } - ); + }, + }); connectable.connect(); }); @@ -75,7 +75,7 @@ describe('multicast', () => { }, }) ) - .subscribe(null, done, done); + .subscribe({ error: done, complete: done }); }); it('should accept Subject factory functions', (done) => { @@ -83,17 +83,17 @@ describe('multicast', () => { const connectable = of(1, 2, 3, 4).pipe(multicast(() => new Subject())) as ConnectableObservable; - connectable.subscribe( - (x) => { + connectable.subscribe({ + next: (x) => { expect(x).to.equal(expected.shift()); }, - () => { + error: () => { done(new Error('should not be called')); }, - () => { + complete: () => { done(); - } - ); + }, + }); connectable.connect(); }); @@ -751,25 +751,23 @@ describe('multicast', () => { const source = of(1, 2, 3, 4).pipe(multicast(() => new Subject())) as ConnectableObservable; - source.subscribe( - (x) => { + source.subscribe({ + next: (x) => { expect(x).to.equal(expected[i++]); }, - null, - () => { + complete: () => { i = 0; - source.subscribe( - (x) => { + source.subscribe({ + next: (x) => { expect(x).to.equal(expected[i++]); }, - null, - done - ); + complete: done, + }); source.connect(); - } - ); + }, + }); source.connect(); }); @@ -784,18 +782,18 @@ describe('multicast', () => { of('a', 'b', 'c') .pipe(switchMap((letter) => source.pipe(map((n) => String(letter + n))))) - .subscribe( - (x) => { + .subscribe({ + next: (x) => { expect(x).to.equal(expected.shift()); }, - () => { + error: () => { done(new Error('should not be called')); }, - () => { + complete: () => { expect(expected.length).to.equal(0); done(); - } - ); + }, + }); }); }); @@ -807,18 +805,18 @@ describe('multicast', () => { of('a', 'b', 'c') .pipe(switchMap((letter) => source.pipe(map((n) => String(letter + n))))) - .subscribe( - (x) => { + .subscribe({ + next: (x) => { expect(x).to.equal(expected.shift()); }, - () => { + error: () => { done(new Error('should not be called')); }, - () => { + complete: () => { expect(expected.length).to.equal(0); done(); - } - ); + }, + }); }); }); }); diff --git a/spec/operators/onErrorResumeNext-spec.ts b/spec/operators/onErrorResumeNext-spec.ts index a0aa755135..7da8ab343a 100644 --- a/spec/operators/onErrorResumeNext-spec.ts +++ b/spec/operators/onErrorResumeNext-spec.ts @@ -215,18 +215,18 @@ describe('onErrorResumeNext', () => { throwError(() => 'meh') ); - source.pipe(onErrorResumeNext(Promise.resolve(2))).subscribe( - (x) => { + source.pipe(onErrorResumeNext(Promise.resolve(2))).subscribe({ + next: (x) => { expect(expected.shift()).to.equal(x); }, - () => { + error: () => { done(new Error('should not be called')); }, - () => { + complete: () => { expect(expected).to.be.empty; done(); - } - ); + }, + }); }); it('should skip invalid sources and move on', () => { diff --git a/spec/operators/publish-spec.ts b/spec/operators/publish-spec.ts index 31efba419f..88fb8e5a83 100644 --- a/spec/operators/publish-spec.ts +++ b/spec/operators/publish-spec.ts @@ -257,14 +257,14 @@ describe('publish operator', () => { expect(results2).to.deep.equal([]); expect(subscriptions).to.equal(1); - connectable.subscribe((x) => { + connectable.subscribe({ next: (x) => { results2.push(x); - }, (x) => { + }, error: (x) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { expect(results2).to.deep.equal([]); done(); - }); + } }); }); it('should multicast an empty source', () => { diff --git a/spec/operators/publishBehavior-spec.ts b/spec/operators/publishBehavior-spec.ts index a6f6d066d5..99594bbf5e 100644 --- a/spec/operators/publishBehavior-spec.ts +++ b/spec/operators/publishBehavior-spec.ts @@ -241,14 +241,14 @@ describe('publishBehavior operator', () => { expect(results2).to.deep.equal([]); expect(subscriptions).to.equal(1); - connectable.subscribe(function (x) { + connectable.subscribe({ next: function (x) { results2.push(x); - }, (x) => { + }, error: (x) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { expect(results2).to.deep.equal([]); done(); - }); + } }); }); it('should multicast an empty source', () => { diff --git a/spec/operators/publishReplay-spec.ts b/spec/operators/publishReplay-spec.ts index 6c396c7c66..38e17640fa 100644 --- a/spec/operators/publishReplay-spec.ts +++ b/spec/operators/publishReplay-spec.ts @@ -371,14 +371,14 @@ describe('publishReplay operator', () => { expect(results2).to.deep.equal([]); expect(subscriptions).to.equal(1); - connectable.subscribe((x) => { + connectable.subscribe({ next: (x) => { results2.push(x); - }, (x) => { + }, error: (x) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { expect(results2).to.deep.equal([3, 4]); done(); - }); + } }); }); it('should multicast an empty source', () => { diff --git a/spec/operators/race-legacy-spec.ts b/spec/operators/race-legacy-spec.ts index ece38dd59d..fb2caf3771 100644 --- a/spec/operators/race-legacy-spec.ts +++ b/spec/operators/race-legacy-spec.ts @@ -168,9 +168,9 @@ describe('race operator', () => { const e1 = of(true); const e2 = timer(200).pipe(map(_ => false)); - e1.pipe(race(e2)).subscribe(x => { + e1.pipe(race(e2)).subscribe({ next: x => { expect(x).to.be.true; - }, done, done); + }, error: done, complete: done }); }); it('should ignore latter observables if a former one emits immediately', () => { diff --git a/spec/operators/raceWith-spec.ts b/spec/operators/raceWith-spec.ts index 47886932e5..5ad6a0f187 100644 --- a/spec/operators/raceWith-spec.ts +++ b/spec/operators/raceWith-spec.ts @@ -154,9 +154,9 @@ describe('raceWith operator', () => { const e1 = of(true); const e2 = timer(200).pipe(map(_ => false)); - e1.pipe(raceWith(e2)).subscribe(x => { + e1.pipe(raceWith(e2)).subscribe({ next: x => { expect(x).to.be.true; - }, done, done); + }, error: done, complete: done }); }); it('should ignore latter observables if a former one emits immediately', () => { diff --git a/spec/operators/repeat-spec.ts b/spec/operators/repeat-spec.ts index 21517857bc..9d157544b3 100644 --- a/spec/operators/repeat-spec.ts +++ b/spec/operators/repeat-spec.ts @@ -331,18 +331,18 @@ describe('repeat operator', () => { refCount(), repeat(5) ) - .subscribe( - (x: number) => { + .subscribe({ + next: (x: number) => { expect(x).to.equal(expected.shift()); }, - (x) => { + error: (x) => { done(new Error('should not be called')); }, - () => { + complete: () => { expect(expected.length).to.equal(0); done(); - } - ); + }, + }); }); it('should stop listening to a synchronous observable when unsubscribed', () => { diff --git a/spec/operators/repeatWhen-spec.ts b/spec/operators/repeatWhen-spec.ts index 2ab972e585..83f2a930e3 100644 --- a/spec/operators/repeatWhen-spec.ts +++ b/spec/operators/repeatWhen-spec.ts @@ -50,13 +50,12 @@ describe('repeatWhen operator', () => { retried = true; return x; }))) - ).subscribe((x: any) => { + ).subscribe({ next: (x: any) => { expect(x).to.equal(expected[i++]); - }, - (err: any) => { + }, error: (err: any) => { expect(err).to.be.an('error', 'done'); done(); - }); + } }); } catch (err) { done(err); } @@ -70,15 +69,15 @@ describe('repeatWhen operator', () => { return n; }), repeatWhen((notifications: any) => EMPTY) - ).subscribe((n: number) => { + ).subscribe({ next: (n: number) => { expect(n).to.equal(expected.shift()); nexted.push(n); - }, (err: any) => { + }, error: (err: any) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { expect(nexted).to.deep.equal([1, 2]); done(); - }); + } }); }); it('should not error when applying an empty synchronous notifier', () => { @@ -103,7 +102,7 @@ describe('repeatWhen operator', () => { }; of(1, 2).pipe( repeatWhen((notifications: any) => EMPTY) - ).subscribe(undefined, err => errors.push(err)); + ).subscribe({ error: err => errors.push(err) }); Observable.prototype.subscribe = originalSubscribe; expect(errors).to.deep.equal([]); }); @@ -130,7 +129,7 @@ describe('repeatWhen operator', () => { }; of(1, 2).pipe( repeatWhen((notifications: any) => of(1)) - ).subscribe(undefined, err => errors.push(err)); + ).subscribe({ error: err => errors.push(err) }); Observable.prototype.subscribe = originalSubscribe; expect(errors).to.deep.equal([]); }); diff --git a/spec/operators/single-spec.ts b/spec/operators/single-spec.ts index 7622186e26..fca74a8ab6 100644 --- a/spec/operators/single-spec.ts +++ b/spec/operators/single-spec.ts @@ -176,9 +176,9 @@ describe('single operator', () => { expectObservable( e1.pipe( single(predicate), - tap(null, null, () => { + tap({ complete: () => { expect(indices).to.deep.equal([0, 1, 2]); - }) + } }) ) ).toBe(expected); expectSubscriptions(e1.subscriptions).toBe(e1subs); @@ -342,7 +342,7 @@ describe('single operator', () => { synchronousObservable.pipe( single(), - ).subscribe(() => { /* noop */ }, () => { /* noop */ }); + ).subscribe({ next: () => { /* noop */ }, error: () => { /* noop */ } }); expect(sideEffects).to.deep.equal([0, 1]); }); diff --git a/spec/operators/takeWhile-spec.ts b/spec/operators/takeWhile-spec.ts index 1884777e4b..edcd51e43a 100644 --- a/spec/operators/takeWhile-spec.ts +++ b/spec/operators/takeWhile-spec.ts @@ -226,8 +226,10 @@ describe('takeWhile', () => { const result = e1.pipe( takeWhile(predicate), - tap(null, null, () => { - expect(invoked).to.equal(3); + tap({ + complete: () => { + expect(invoked).to.equal(3); + }, }) ); expectObservable(result).toBe(expected); diff --git a/spec/operators/tap-spec.ts b/spec/operators/tap-spec.ts index f84b199217..6c6e8829c8 100644 --- a/spec/operators/tap-spec.ts +++ b/spec/operators/tap-spec.ts @@ -47,8 +47,10 @@ describe('tap', () => { let err = null; throwError(() => 'bad') .pipe( - tap(null, function (x) { - err = x; + tap({ + error: function (x) { + err = x; + }, }) ) .subscribe({ @@ -107,8 +109,10 @@ describe('tap', () => { let errored = false; throwError(() => 'bad') .pipe( - tap(null, (err: any) => { - expect(err).to.equal('bad'); + tap({ + error: (err: any) => { + expect(err).to.equal('bad'); + }, }) ) .subscribe({ diff --git a/spec/operators/throttleTime-spec.ts b/spec/operators/throttleTime-spec.ts index 79d376fc35..3f87106628 100644 --- a/spec/operators/throttleTime-spec.ts +++ b/spec/operators/throttleTime-spec.ts @@ -31,13 +31,12 @@ describe('throttleTime operator', () => { it('should throttle events by 5 time units', (done) => { of(1, 2, 3) .pipe(throttleTime(5)) - .subscribe( - (x: number) => { + .subscribe({ + next: (x: number) => { expect(x).to.equal(1); }, - null, - done - ); + complete: done, + }); }); it('should throttle events multiple times', () => { diff --git a/spec/operators/timeout-spec.ts b/spec/operators/timeout-spec.ts index 59a894980d..ebedfdac82 100644 --- a/spec/operators/timeout-spec.ts +++ b/spec/operators/timeout-spec.ts @@ -35,17 +35,17 @@ describe('timeout operator', () => { const t = time(' -----|'); const result = e1.pipe(timeout(t, rxTestScheduler)); let error: any; - result.subscribe( - () => { + result.subscribe({ + next: () => { throw new Error('this should not next'); }, - (err) => { + error: (err) => { error = err; }, - () => { + complete: () => { throw new Error('this should not complete'); - } - ); + }, + }); rxTestScheduler.flush(); expect(error).to.be.an.instanceof(TimeoutError); expect(error).to.have.property('name', 'TimeoutError'); @@ -67,17 +67,17 @@ describe('timeout operator', () => { const result = e1.pipe(timeout(dueDate, rxTestScheduler)); let error: any; - result.subscribe( - () => { + result.subscribe({ + next: () => { throw new Error('this should not next'); }, - (err) => { + error: (err) => { error = err; }, - () => { + complete: () => { throw new Error('this should not complete'); - } - ); + }, + }); rxTestScheduler.flush(); expect(error).to.be.an.instanceof(TimeoutError); expect(error).to.have.property('name', 'TimeoutError'); @@ -210,17 +210,17 @@ describe('timeout operator', () => { const t = time(' -----|'); const result = e1.pipe(timeout({ each: t })); let error: any; - result.subscribe( - () => { + result.subscribe({ + next: () => { throw new Error('this should not next'); }, - (err) => { + error: (err) => { error = err; }, - () => { + complete: () => { throw new Error('this should not complete'); - } - ); + }, + }); rxTestScheduler.flush(); expect(error).to.be.an.instanceof(TimeoutError); expect(error).to.have.property('name', 'TimeoutError'); @@ -242,17 +242,17 @@ describe('timeout operator', () => { const result = e1.pipe(timeout({ first: dueDate })); let error: any; - result.subscribe( - () => { + result.subscribe({ + next: () => { throw new Error('this should not next'); }, - (err) => { + error: (err) => { error = err; }, - () => { + complete: () => { throw new Error('this should not complete'); - } - ); + }, + }); rxTestScheduler.flush(); expect(error).to.be.an.instanceof(TimeoutError); expect(error).to.have.property('name', 'TimeoutError'); @@ -423,10 +423,12 @@ describe('timeout operator', () => { const innerSubs = ' -----^-----! '; const expected = ' -----x-y-z-| '; - const result = source.pipe(timeout({ - each: t, - with: () => inner, - })); + const result = source.pipe( + timeout({ + each: t, + with: () => inner, + }) + ); expectObservable(result).toBe(expected); expectSubscriptions(source.subscriptions).toBe(sourceSubs); @@ -444,10 +446,12 @@ describe('timeout operator', () => { const expected = ' ------------x--y--z--|'; // The the current frame is zero. - const result = source.pipe(timeout({ - first: new Date(t), - with: () => inner, - })); + const result = source.pipe( + timeout({ + first: new Date(t), + with: () => inner, + }) + ); expectObservable(result).toBe(expected); expectSubscriptions(source.subscriptions).toBe(sourceSubs); @@ -464,9 +468,12 @@ describe('timeout operator', () => { const innerSubs = ' -----------^----! '; const expected = ' ---a---b----x-y-| '; - const result = source.pipe(timeout({ - each: t, - with: () => inner, })); + const result = source.pipe( + timeout({ + each: t, + with: () => inner, + }) + ); expectObservable(result).toBe(expected); expectSubscriptions(source.subscriptions).toBe(sourceSubs); @@ -504,7 +511,7 @@ describe('timeout operator', () => { const result = source.pipe( mergeMap((x) => of(x)), - timeout({ each: t, with: () => inner, }), + timeout({ each: t, with: () => inner }), mergeMap((x) => of(x)) ); @@ -544,7 +551,7 @@ describe('timeout operator', () => { const innerSubs = ' ----------^--------!'; const expected = ' --------------x----|'; - const result = source.pipe(timeout({ each: t, with: () => inner, })); + const result = source.pipe(timeout({ each: t, with: () => inner })); expectObservable(result).toBe(expected); expectSubscriptions(source.subscriptions).toBe(sourceSubs); @@ -561,7 +568,7 @@ describe('timeout operator', () => { const innerSubs = ' ---------^-----------'; const expected = ' --a--b---------------'; - const result = source.pipe(timeout({ each: t, with: () => inner, })); + const result = source.pipe(timeout({ each: t, with: () => inner })); expectObservable(result).toBe(expected); expectSubscriptions(source.subscriptions).toBe(sourceSubs); @@ -578,7 +585,7 @@ describe('timeout operator', () => { const innerSubs = ' ----------^--------!'; const expected = ' --------------x----|'; - const result = source.pipe(timeout({ each: t, with: () => inner, })); + const result = source.pipe(timeout({ each: t, with: () => inner })); expectObservable(result).toBe(expected); expectSubscriptions(source.subscriptions).toBe(sourceSubs); @@ -688,7 +695,7 @@ describe('timeout operator', () => { it('should stop listening to a synchronous observable when unsubscribed', () => { const sideEffects: number[] = []; - const synchronousObservable = new Observable(subscriber => { + const synchronousObservable = new Observable((subscriber) => { // This will check to see if the subscriber was closed on each loop // when the unsubscribe hits (from the `take`), it should be closed for (let i = 0; !subscriber.closed && i < 10; i++) { @@ -697,10 +704,9 @@ describe('timeout operator', () => { } }); - synchronousObservable.pipe( - timeout(0), - take(3), - ).subscribe(() => { /* noop */ }); + synchronousObservable.pipe(timeout(0), take(3)).subscribe(() => { + /* noop */ + }); expect(sideEffects).to.deep.equal([0, 1, 2]); }); diff --git a/spec/schedulers/TestScheduler-spec.ts b/spec/schedulers/TestScheduler-spec.ts index ce3b515cef..686095ea23 100644 --- a/spec/schedulers/TestScheduler-spec.ts +++ b/spec/schedulers/TestScheduler-spec.ts @@ -224,11 +224,11 @@ describe('TestScheduler', () => { it('should create a cold observable', () => { const expected = [1, 2]; const source = cold('-a-b-|', { a: 1, b: 2 }); - source.subscribe((x: number) => { + source.subscribe({ next: (x: number) => { expect(x).to.equal(expected.shift()); - }, null, () => { + }, complete: () => { expect(expected.length).to.equal(0); - }); + } }); expectObservable(source).toBe('-a-b-|', { a: 1, b: 2 }); }); }); diff --git a/spec/subjects/BehaviorSubject-spec.ts b/spec/subjects/BehaviorSubject-spec.ts index d7b1c04c32..ff5c2d2882 100644 --- a/spec/subjects/BehaviorSubject-spec.ts +++ b/spec/subjects/BehaviorSubject-spec.ts @@ -63,9 +63,9 @@ describe('BehaviorSubject', () => { const expected = ['foo', 'bar']; let i = 0; - subject.subscribe((x: string) => { + subject.subscribe({ next: (x: string) => { expect(x).to.equal(expected[i++]); - }, null, done); + }, complete: done }); subject.next('bar'); subject.complete(); @@ -81,9 +81,9 @@ describe('BehaviorSubject', () => { expect(x).to.equal(expected[i++]); }); - subject.subscribe((x: string) => { + subject.subscribe({ next: (x: string) => { expect(x).to.equal(expected[j++]); - }, null, done); + }, complete: done }); expect(subject.observers.length).to.equal(2); subject.next('foo'); @@ -147,7 +147,7 @@ describe('BehaviorSubject', () => { expectObservable(hot(sourceTemplate).pipe( tap( - feedNextIntoSubject, feedErrorIntoSubject, feedCompleteIntoSubject + { next: feedNextIntoSubject, error: feedErrorIntoSubject, complete: feedCompleteIntoSubject } ) )).toBe(sourceTemplate); expectObservable(subscriber1, unsub1).toBe(expected1); @@ -169,7 +169,7 @@ describe('BehaviorSubject', () => { expectObservable(hot(sourceTemplate).pipe( tap( - feedNextIntoSubject, feedErrorIntoSubject, feedCompleteIntoSubject + { next: feedNextIntoSubject, error: feedErrorIntoSubject, complete: feedCompleteIntoSubject } ) )).toBe(sourceTemplate); expectObservable(subscriber1).toBe(expected1); @@ -181,14 +181,14 @@ describe('BehaviorSubject', () => { const expected = [0, 1, 2, 3, 4, 5]; subject.subscribe( - (x: number) => { + { next: (x: number) => { expect(x).to.equal(expected.shift()); - }, (x) => { + }, error: (x) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { expect(subject.value).to.equal(5); done(); - }); + } }); source.subscribe(subject); }); @@ -203,14 +203,14 @@ describe('BehaviorSubject', () => { const expected = [0, 1, 2, 3, 4, 5]; subject.subscribe( - (x: number) => { + { next: (x: number) => { expect(x).to.equal(expected.shift()); - }, (x) => { + }, error: (x) => { done(new Error('should not be called')); - }, () => { + }, complete: () => { expect(subject.value).to.equal(5); done(); - }); + } }); source.subscribe(asInteropSubject(subject)); }); diff --git a/spec/subjects/ReplaySubject-spec.ts b/spec/subjects/ReplaySubject-spec.ts index 90a8271d48..e86f05e47c 100644 --- a/spec/subjects/ReplaySubject-spec.ts +++ b/spec/subjects/ReplaySubject-spec.ts @@ -40,18 +40,16 @@ describe('ReplaySubject', () => { subject.next(2); subject.next(3); subject.subscribe( - (x: number) => { + { next: (x: number) => { expect(x).to.equal(expects[i++]); if (i === 3) { subject.complete(); } - }, - (err: any) => { + }, error: (err: any) => { done(new Error('should not be called')); - }, - () => { + }, complete: () => { done(); - } + } } ); }); @@ -64,11 +62,9 @@ describe('ReplaySubject', () => { subject.next(3); subject.complete(); subject.subscribe( - (x: number) => { + { next: (x: number) => { expect(x).to.equal(expects[i++]); - }, - null, - done + }, complete: done } ); }); @@ -81,13 +77,12 @@ describe('ReplaySubject', () => { subject.next(3); subject.error('fooey'); subject.subscribe( - (x: number) => { + { next: (x: number) => { expect(x).to.equal(expects[i++]); - }, - (err: any) => { + }, error: (err: any) => { expect(err).to.equal('fooey'); done(); - } + } } ); }); @@ -99,18 +94,16 @@ describe('ReplaySubject', () => { subject.next(2); subject.next(3); subject.subscribe( - (x: number) => { + { next: (x: number) => { expect(x).to.equal(expects[i++]); if (i === 2) { subject.complete(); } - }, - (err: any) => { + }, error: (err: any) => { done(new Error('should not be called')); - }, - () => { + }, complete: () => { done(); - } + } } ); }); @@ -138,7 +131,7 @@ describe('ReplaySubject', () => { const subscriber3 = hot('---------------------------(c|) ').pipe(mergeMapTo(replaySubject)); const expected3 = ' ---------------------------(78)9--|'; - expectObservable(hot(sourceTemplate).pipe(tap(feedNextIntoSubject, feedErrorIntoSubject, feedCompleteIntoSubject))).toBe( + expectObservable(hot(sourceTemplate).pipe(tap({ next: feedNextIntoSubject, error: feedErrorIntoSubject, complete: feedCompleteIntoSubject }))).toBe( sourceTemplate ); expectObservable(subscriber1, unsub1).toBe(expected1); @@ -164,7 +157,7 @@ describe('ReplaySubject', () => { const subscriber1 = hot('---------------(a|) ').pipe(mergeMapTo(replaySubject)); const expected1 = ' ---------------(34|)'; - expectObservable(hot(sourceTemplate).pipe(tap(feedNextIntoSubject, feedErrorIntoSubject, feedCompleteIntoSubject))).toBe( + expectObservable(hot(sourceTemplate).pipe(tap({ next: feedNextIntoSubject, error: feedErrorIntoSubject, complete: feedCompleteIntoSubject }))).toBe( sourceTemplate ); expectObservable(subscriber1).toBe(expected1); @@ -183,29 +176,25 @@ describe('ReplaySubject', () => { subject.next(4); const subscription1 = subject.subscribe( - (x: number) => { + { next: (x: number) => { results1.push(x); - }, - (err: any) => { + }, error: (err: any) => { results1.push('E'); - }, - () => { + }, complete: () => { results1.push('C'); - } + } } ); subject.next(5); const subscription2 = subject.subscribe( - (x: number) => { + { next: (x: number) => { results2.push(x); - }, - (err: any) => { + }, error: (err: any) => { results2.push('E'); - }, - () => { + }, complete: () => { results2.push('C'); - } + } } ); subject.next(6); @@ -221,15 +210,13 @@ describe('ReplaySubject', () => { subject.next(10); const subscription3 = subject.subscribe( - (x: number) => { + { next: (x: number) => { results3.push(x); - }, - (err: any) => { + }, error: (err: any) => { results3.push('E'); - }, - () => { + }, complete: () => { results3.push('C'); - } + } } ); subject.next(11); @@ -268,7 +255,7 @@ describe('ReplaySubject', () => { const subscriber3 = hot('---------------------------(c|) ').pipe(mergeMapTo(replaySubject)); const expected3 = ' ---------------------------(78)9--|'; - expectObservable(hot(sourceTemplate).pipe(tap(feedNextIntoSubject, feedErrorIntoSubject, feedCompleteIntoSubject))).toBe( + expectObservable(hot(sourceTemplate).pipe(tap({ next: feedNextIntoSubject, error: feedErrorIntoSubject, complete: feedCompleteIntoSubject }))).toBe( sourceTemplate ); expectObservable(subscriber1, unsub1).toBe(expected1); @@ -294,7 +281,7 @@ describe('ReplaySubject', () => { const subscriber1 = hot('-------------(a|)').pipe(mergeMapTo(replaySubject)); const expected1 = ' -------------(4|)'; - expectObservable(hot(sourceTemplate).pipe(tap(feedNextIntoSubject, feedErrorIntoSubject, feedCompleteIntoSubject))).toBe( + expectObservable(hot(sourceTemplate).pipe(tap({ next: feedNextIntoSubject, error: feedErrorIntoSubject, complete: feedCompleteIntoSubject }))).toBe( sourceTemplate ); expectObservable(subscriber1).toBe(expected1); @@ -318,7 +305,7 @@ describe('ReplaySubject', () => { const subscriber1 = hot('----(a|)').pipe(mergeMapTo(replaySubject)); const expected1 = ' ----(34)---|'; - expectObservable(hot(sourceTemplate).pipe(tap(feedNextIntoSubject, feedErrorIntoSubject, feedCompleteIntoSubject))).toBe( + expectObservable(hot(sourceTemplate).pipe(tap({ next: feedNextIntoSubject, error: feedErrorIntoSubject, complete: feedCompleteIntoSubject }))).toBe( sourceTemplate ); expectObservable(subscriber1).toBe(expected1); @@ -332,9 +319,7 @@ describe('ReplaySubject', () => { let results: (number | string)[] = []; subject.subscribe( - (x) => results.push(x), - null, - () => results.push('done') + { next: (x) => results.push(x), complete: () => results.push('done') } ); source.subscribe(subject); @@ -344,9 +329,7 @@ describe('ReplaySubject', () => { results = []; subject.subscribe( - (x) => results.push(x), - null, - () => results.push('done') + { next: (x) => results.push(x), complete: () => results.push('done') } ); expect(results).to.deep.equal([3, 4, 5, 'done']); diff --git a/src/internal/Observable.ts b/src/internal/Observable.ts index abab383605..02ab4b4ff2 100644 --- a/src/internal/Observable.ts +++ b/src/internal/Observable.ts @@ -1,6 +1,3 @@ -/** - * @prettier - */ import { Operator } from './Operator'; import { SafeSubscriber, Subscriber } from './Subscriber'; import { isSubscription, Subscription } from './Subscription'; @@ -124,8 +121,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 +147,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 +170,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 +199,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 +261,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 @@ -419,10 +420,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( @@ -430,7 +431,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 e54e2cbd4c..43cf53cc27 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 = (() => { @@ -274,14 +292,23 @@ const LOADSTART = 'loadstart'; const PROGRESS = 'progress'; const LOAD = 'load'; -export function fromAjax(config: AjaxConfig): Observable> { +export function fromAjax(init: AjaxConfig): Observable> { 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. - const { queryParams, body: configuredBody, headers: configuredHeaders, ...remainingConfig } = config; + const config = { + // Defaults + async: true, + crossDomain: false, + withCredentials: false, + method: 'GET', + timeout: 0, + responseType: 'json' as XMLHttpRequestResponseType, + + ...init, + }; - let { url } = remainingConfig; + const { queryParams, body: configuredBody, headers: configuredHeaders } = config; + + let url = config.url; if (!url) { throw new TypeError('url is required'); } @@ -327,6 +354,8 @@ export function fromAjax(config: AjaxConfig): Observable> { } } + const crossDomain = config.crossDomain; + // Set the x-requested-with header. This is a non-standard header that has // come to be a de facto standard for HTTP requests sent by libraries and frameworks // using XHR. However, we DO NOT want to set this if it is a CORS request. This is @@ -334,14 +363,14 @@ export function fromAjax(config: AjaxConfig): Observable> { // None of this is necessary, it's only being set because it's "the thing libraries do" // Starting back as far as JQuery, and continuing with other libraries such as Angular 1, // Axios, et al. - if (!config.crossDomain && !('x-requested-with' in headers)) { + if (!crossDomain && !('x-requested-with' in headers)) { headers['x-requested-with'] = 'XMLHttpRequest'; } // Allow users to provide their XSRF cookie name and the name of a custom header to use to // send the cookie. - const { withCredentials, xsrfCookieName, xsrfHeaderName } = remainingConfig; - if ((withCredentials || !remainingConfig.crossDomain) && xsrfCookieName && xsrfHeaderName) { + const { withCredentials, xsrfCookieName, xsrfHeaderName } = config; + if ((withCredentials || !crossDomain) && xsrfCookieName && xsrfHeaderName) { const xsrfCookie = document?.cookie.match(new RegExp(`(^|;\\s*)(${xsrfCookieName})=([^;]*)`))?.pop() ?? ''; if (xsrfCookie) { headers[xsrfHeaderName] = xsrfCookie; @@ -352,17 +381,9 @@ export function fromAjax(config: AjaxConfig): Observable> { // and set the content-type in `headers`, if we're able. const body = extractContentTypeAndMaybeSerializeBody(configuredBody, headers); - const _request: AjaxRequest = { - // Default values - async: true, - crossDomain: true, - withCredentials: false, - method: 'GET', - timeout: 0, - responseType: 'json' as XMLHttpRequestResponseType, - - // Override with passed user values - ...remainingConfig, + // The final request settings. + const _request: Readonly = { + ...config, // Set values we ensured above url, @@ -373,7 +394,7 @@ export function fromAjax(config: AjaxConfig): Observable> { let xhr: XMLHttpRequest; // Create our XHR so we can get started. - xhr = config.createXHR ? config.createXHR() : new XMLHttpRequest(); + xhr = init.createXHR ? init.createXHR() : new XMLHttpRequest(); { /////////////////////////////////////////////////// @@ -383,7 +404,7 @@ export function fromAjax(config: AjaxConfig): Observable> { // Otherwise the progress events will not fire. /////////////////////////////////////////////////// - const { progressSubscriber, includeDownloadProgress = false, includeUploadProgress = false } = config; + const { progressSubscriber, includeDownloadProgress = false, includeUploadProgress = false } = init; /** * Wires up an event handler that will emit an error when fired. Used diff --git a/src/internal/ajax/types.ts b/src/internal/ajax/types.ts index 0d932e300e..96e8a91109 100644 --- a/src/internal/ajax/types.ts +++ b/src/internal/ajax/types.ts @@ -133,6 +133,14 @@ export interface AjaxConfig { /** * Whether or not to send the HTTP request as a CORS request. * Defaults to `false`. + * + * @deprecated Will be removed in version 8. Cross domain requests and what creates a cross + * domain request, are dictated by the browser, and a boolean that forces it to be cross domain + * does not make sense. If you need to force cross domain, make sure you're making a secure request, + * then add a custom header to the request or use `withCredentials`. For more information on what + * triggers a cross domain request, see the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials). + * In particular, the section on [Simple Requests](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests) is useful + * for understanding when CORS will not be used. */ crossDomain?: boolean; diff --git a/src/internal/firstValueFrom.ts b/src/internal/firstValueFrom.ts index de6e237c63..2fc4bcfe43 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} diff --git a/src/internal/lastValueFrom.ts b/src/internal/lastValueFrom.ts index b70000f47e..90fcebfb3e 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} diff --git a/src/internal/observable/combineLatest.ts b/src/internal/observable/combineLatest.ts index b207405fe9..f99da47d4d 100644 --- a/src/internal/observable/combineLatest.ts +++ b/src/internal/observable/combineLatest.ts @@ -110,9 +110,11 @@ 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'; + * import { timer, combineLatest } from 'rxjs'; * * const firstTimer = timer(0, 1000); // emit 0, 1, 2... after every second, starting from now * const secondTimer = timer(500, 1000); // emit 0, 1, 2... after every second, starting 0,5s from now @@ -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); diff --git a/src/internal/observable/concat.ts b/src/internal/observable/concat.ts index 230c1a7bb9..75f9722f02 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 417f867790..2e54b37246 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); diff --git a/src/internal/observable/dom/WebSocketSubject.ts b/src/internal/observable/dom/WebSocketSubject.ts index 118e15da72..036aca1278 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; /** diff --git a/src/internal/observable/dom/animationFrames.ts b/src/internal/observable/dom/animationFrames.ts index 7ac4bfca82..707174f9c0 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 bc04708823..a2a01359f6 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. * - * ### Basic Use + * ## 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, diff --git a/src/internal/observable/dom/webSocket.ts b/src/internal/observable/dom/webSocket.ts index e11560748c..d642f0b4b3 100644 --- a/src/internal/observable/dom/webSocket.ts +++ b/src/internal/observable/dom/webSocket.ts @@ -82,51 +82,58 @@ 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(); * // Note that at least one consumer has to subscribe to the created subject - otherwise "nexted" values will be just buffered and not sent, * // since no connection was established! * - * subject.next({message: 'some message'}); + * subject.next({ message: 'some message' }); * // This will send a message to the server once a connection is made. Remember value is serialized with JSON.stringify by default! * * subject.complete(); // Closes the connection. * - * subject.error({code: 4000, reason: 'I think our app just broke!'}); + * subject.error({ code: 4000, reason: 'I think our app just broke!' }); * // 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' * ); * @@ -146,7 +153,6 @@ import { WebSocketSubject, WebSocketSubjectConfig } from './WebSocketSubject'; * // socket connection closes. * ``` * - * * @param {string|WebSocketSubjectConfig} urlConfigOrSource The WebSocket endpoint as an url or an object with * configuration and additional Observers. * @return {WebSocketSubject} Subject which allows to both send and receive messages via WebSocket connection. diff --git a/src/internal/observable/empty.ts b/src/internal/observable/empty.ts index 14edd1a2b9..d6fb8684a0 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'; @@ -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( diff --git a/src/internal/observable/forkJoin.ts b/src/internal/observable/forkJoin.ts index ab5a5a19e9..23f4d76026 100644 --- a/src/internal/observable/forkJoin.ts +++ b/src/internal/observable/forkJoin.ts @@ -94,14 +94,15 @@ 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'; * * const observable = forkJoin({ * foo: of(1, 2, 3, 4), * bar: Promise.resolve(8), - * baz: timer(4000), + * baz: timer(4000) * }); * observable.subscribe({ * next: value => console.log(value), @@ -110,17 +111,18 @@ 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'; * * const observable = forkJoin([ * of(1, 2, 3, 4), * Promise.resolve(8), - * timer(4000), + * timer(4000) * ]); * observable.subscribe({ * next: value => console.log(value), @@ -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} diff --git a/src/internal/observable/from.ts b/src/internal/observable/from.ts index 1bbea4dd92..834bb22852 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'; @@ -89,8 +84,8 @@ export function from>(input: O, scheduler: Schedu * console.log('end'); * * // Logs: - * // start - * // end + * // 'start' + * // 'end' * // 10 * // 20 * // 30 diff --git a/src/internal/observable/fromEvent.ts b/src/internal/observable/fromEvent.ts index 8044ff9da9..0dd31bfe4b 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'; * diff --git a/src/internal/observable/fromEventPattern.ts b/src/internal/observable/fromEventPattern.ts index 92f5e45ab0..fee384765f 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,26 +100,25 @@ export function fromEventPattern( * ); * ``` * - * ## Example - * ### Use with project function + * Use with project function * * ```ts * import { fromEventPattern } from 'rxjs'; * * someAPI.registerEventHandler((eventType, eventMessage) => { - * console.log(eventType, eventMessage); // Logs "EVENT_TYPE" "EVENT_MESSAGE" to console. + * console.log(eventType, eventMessage); // Logs 'EVENT_TYPE' 'EVENT_MESSAGE' to console. * }); * * const someAPIObservable = fromEventPattern( * handler => someAPI.registerEventHandler(handler), * handler => someAPI.unregisterEventHandler(handler) - * (eventType, eventMessage) => eventType + " --- " + eventMessage // without that function only "EVENT_TYPE" + * (eventType, eventMessage) => eventType + ' --- ' + eventMessage // without that function only 'EVENT_TYPE' * ); // would be emitted by the Observable * * someAPIObservable.subscribe(value => console.log(value)); * * // Logs: - * // "EVENT_TYPE --- EVENT_MESSAGE" + * // 'EVENT_TYPE --- EVENT_MESSAGE' * ``` * * @see {@link fromEvent} diff --git a/src/internal/observable/generate.ts b/src/internal/observable/generate.ts index ed467e0703..e8af3036fd 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'; @@ -265,19 +264,19 @@ export function generate( * const result = generate({ * initialState: 0, * condition: x => x < 3, - * iterate: x => x + 1, + * iterate: x => x + 1 * }); * * 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'; @@ -308,19 +307,19 @@ export function generate(options: GenerateBaseOptions): Observable; * initialState: 0, * condition: x => x < 3, * iterate: x => x + 1, - * resultSelector: x => x, + * resultSelector: x => x * }); * * 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 d1e8e6544a..56ede0c250 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'; @@ -25,52 +25,52 @@ import { ObservableInput } from '../types'; * const firstOrSecond = iif( * () => subscribeToFirst, * of('first'), - * of('second'), + * of('second') * ); * * subscribeToFirst = true; * 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 9b195134bd..fc1b3e0a77 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 268c03363b..38adf345dc 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 ead9ba1895..cfbec7de94 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 7f9fe21380..dc0c918236 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 fe945c26b2..60fbceca39 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 071879bce8..4dafb9ffb8 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 1c3c9dfa9b..d69db663f5 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 2093ad926e..adb02c0088 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' diff --git a/src/internal/observable/range.ts b/src/internal/observable/range.ts index 834e393932..314ac1bed6 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. diff --git a/src/internal/observable/throwError.ts b/src/internal/observable/throwError.ts index 8faab39be4..a307f5ad95 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 + * ### 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 * }); * ``` * diff --git a/src/internal/observable/timer.ts b/src/internal/observable/timer.ts index 361e7730d9..dcc2745811 100644 --- a/src/internal/observable/timer.ts +++ b/src/internal/observable/timer.ts @@ -18,7 +18,7 @@ import { isValidDate } from '../util/isDate'; * * ## Examples * - * ### Wait 3 seconds and start another observable + * Wait 3 seconds and start another observable * * You might want to use `timer` to delay subscription to an * observable by a set amount of time. Here we use a timer with @@ -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. diff --git a/src/internal/observable/zip.ts b/src/internal/observable/zip.ts index 4301089cd4..df46590e0b 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} */ diff --git a/src/internal/operators/audit.ts b/src/internal/operators/audit.ts index e8bdfa000f..eb8c376f73 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} diff --git a/src/internal/operators/auditTime.ts b/src/internal/operators/auditTime.ts index 7777ddce18..af83889db9 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 e7631aaecb..1a911019c2 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); diff --git a/src/internal/operators/bufferCount.ts b/src/internal/operators/bufferCount.ts index ee7bf6844a..553e77bd3d 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)); diff --git a/src/internal/operators/bufferTime.ts b/src/internal/operators/bufferTime.ts index cab6dd2b21..afc6c1d045 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 61d3613570..c69cd7b802 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); diff --git a/src/internal/operators/bufferWhen.ts b/src/internal/operators/bufferWhen.ts index fd8638e09b..6311091305 100644 --- a/src/internal/operators/bufferWhen.ts +++ b/src/internal/operators/bufferWhen.ts @@ -24,17 +24,15 @@ 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(() => - * interval(1000 + Math.random() * 4000) - * )); + * const buffered = clicks.pipe( + * bufferWhen(() => interval(1000 + Math.random() * 4000)) + * ); * buffered.subscribe(x => console.log(x)); * ``` * - * * @see {@link buffer} * @see {@link bufferCount} * @see {@link bufferTime} diff --git a/src/internal/operators/catchError.ts b/src/internal/operators/catchError.ts index 7a69d49774..574a6c62ea 100644 --- a/src/internal/operators/catchError.ts +++ b/src/internal/operators/catchError.ts @@ -28,52 +28,53 @@ 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 + * + * Continue 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 * ``` * - * Retries the caught source Observable again in case of error, similar to retry() operator + * Retry 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, ... * ``` * - * Throws a new error when the source Observable throws an error + * Throw 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! * ``` * diff --git a/src/internal/operators/combineLatestAll.ts b/src/internal/operators/combineLatestAll.ts index 7d06b87bcc..25569a9e81 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(() => 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 7a6b177dad..b262f890b8 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 727b7f1bd3..05be4fc9c9 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(() => 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 7dfbac5bcf..21bbf42431 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 e0142721dc..b7503c3b9f 100644 --- a/src/internal/operators/concatMapTo.ts +++ b/src/internal/operators/concatMapTo.ts @@ -3,12 +3,12 @@ import { ObservableInput, OperatorFunction, ObservedValueOf } from '../types'; import { isFunction } from '../util/isFunction'; /* tslint:disable:max-line-length */ -export function concatMapTo>(observable: O): OperatorFunction>; +export function concatMapTo>(observable: O): OperatorFunction>; /** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */ export function concatMapTo>( observable: O, resultSelector: undefined -): OperatorFunction>; +): OperatorFunction>; /** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */ export function concatMapTo>( observable: O, @@ -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 6fd4b8f36f..b836b29e22 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 4c497c91d9..d422ab5eb3 100644 --- a/src/internal/operators/connect.ts +++ b/src/internal/operators/connect.ts @@ -11,7 +11,7 @@ import { fromSubscribable } from '../observable/fromSubscribable'; export interface ConnectConfig { /** * A factory function used to create the Subject through which the source - * is multicast. By default this creates a {@link Subject}. + * is multicast. By default, this creates a {@link Subject}. */ connector: () => SubjectLike; } @@ -46,55 +46,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, map, filter } 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 81d037be3f..8b764f8332 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 1724904c87..05cf58e4d4 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 875116fe88..40f385caad 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 53f99b055f..eb27f463ec 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))); diff --git a/src/internal/operators/delay.ts b/src/internal/operators/delay.ts index 5758c95016..299259b0e9 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 208438fffb..3d350735a4 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 2c6e8e3d8b..913e4f0ad8 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: NextNotification = { kind: 'N', value: 'A' }; + * const notifB: NextNotification = { kind: 'N', value: 'B' }; + * const notifE: ErrorNotification = { 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 diff --git a/src/internal/operators/distinct.ts b/src/internal/operators/distinct.ts index b713204fdc..75eca965e7 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' } diff --git a/src/internal/operators/distinctUntilChanged.ts b/src/internal/operators/distinctUntilChanged.ts index 30f87bcc96..e7d2f46048 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); * @@ -112,13 +104,15 @@ export function distinctUntilChanged(comparator?: (previous: T, current: T) = * the account changed hands... * * ```ts + * import { of, distinctUntilChanged } from 'rxjs'; + * * // 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 +122,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 diff --git a/src/internal/operators/distinctUntilKeyChanged.ts b/src/internal/operators/distinctUntilKeyChanged.ts index 45112b9219..0f67082601 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' } diff --git a/src/internal/operators/elementAt.ts b/src/internal/operators/elementAt.ts index 21454089e0..6a817fc5dd 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 ed5e0985c1..436e5b301a 100644 --- a/src/internal/operators/endWith.ts +++ b/src/internal/operators/endWith.ts @@ -31,11 +31,10 @@ 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'), + * map(() => 'tick') * ); * * const documentClicks$ = fromEvent(document, 'click'); @@ -43,26 +42,26 @@ export function endWith(...values: A): OperatorFun * ticker$.pipe( * startWith('interval started'), * takeUntil(documentClicks$), - * endWith('interval ended by click'), + * endWith('interval ended by click') * ) * .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 c7c52d4bcb..aa07bee306 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. diff --git a/src/internal/operators/exhaustAll.ts b/src/internal/operators/exhaustAll.ts index d5ebd59fa4..ac30d6d1d0 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)); diff --git a/src/internal/operators/exhaustMap.ts b/src/internal/operators/exhaustMap.ts index b2ea51b6f4..523266bb4e 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)); * ``` diff --git a/src/internal/operators/expand.ts b/src/internal/operators/expand.ts index b79f6376e2..84b7e347a6 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 97d5e8b62d..35a3a0aa00 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;`; + * 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)); * ``` * diff --git a/src/internal/operators/finalize.ts b/src/internal/operators/finalize.ts index aa4575be35..7ab08b239c 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 89952ce621..049ef4c932 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)); * ``` * diff --git a/src/internal/operators/findIndex.ts b/src/internal/operators/findIndex.ts index 6016493f90..7a9d943cbc 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 4339bd8c34..b3ca1f8e46 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 39c7a4a10f..2bd0740dc6 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: 3, name: 'TSLint'} ] + * // [{ 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' ] } diff --git a/src/internal/operators/ignoreElements.ts b/src/internal/operators/ignoreElements.ts index 8df5dd0ec6..2663f7ff18 100644 --- a/src/internal/operators/ignoreElements.ts +++ b/src/internal/operators/ignoreElements.ts @@ -8,34 +8,37 @@ 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. */ -export function ignoreElements(): OperatorFunction { +export function ignoreElements(): OperatorFunction { return operate((source, subscriber) => { source.subscribe(new OperatorSubscriber(subscriber, noop)); }); diff --git a/src/internal/operators/isEmpty.ts b/src/internal/operators/isEmpty.ts index 4c7996b906..ea730a4cab 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()); @@ -40,17 +39,16 @@ import { OperatorSubscriber } from './OperatorSubscriber'; * source.complete(); * * // Outputs - * // a + * // 'a' * // false - * // b - * // c + * // 'b' + * // '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 5117db061a..a046922f87 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 3e4e513558..59a3377371 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 4608b00d05..1caab7eac3 100644 --- a/src/internal/operators/mapTo.ts +++ b/src/internal/operators/mapTo.ts @@ -1,7 +1,7 @@ import { OperatorFunction } from '../types'; import { map } from './map'; -export function mapTo(value: R): OperatorFunction; +export function mapTo(value: R): OperatorFunction; /** @deprecated Do not specify explicit type parameters. Signatures with type parameters that cannot be inferred will be removed in v8. */ export function mapTo(value: R): OperatorFunction; @@ -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)); * ``` * @@ -35,6 +37,6 @@ export function mapTo(value: R): OperatorFunction; * @return A function that returns an Observable that emits the given `value` * every time the source Observable emits. */ -export function mapTo(value: R): OperatorFunction { +export function mapTo(value: R): OperatorFunction { return map(() => value); } diff --git a/src/internal/operators/materialize.ts b/src/internal/operators/materialize.ts index 70257b9bfe..b7f094d835 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} diff --git a/src/internal/operators/max.ts b/src/internal/operators/max.ts index 744ff8ea5e..b3c5fcbc77 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 c5fb539ff9..9183badacb 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 b159bda883..6a8807618f 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 d22a0c718e..4a2eeeedbf 100644 --- a/src/internal/operators/mergeMapTo.ts +++ b/src/internal/operators/mergeMapTo.ts @@ -6,7 +6,7 @@ import { isFunction } from '../util/isFunction'; export function mergeMapTo>( innerObservable: O, concurrent?: number -): OperatorFunction>; +): OperatorFunction>; /** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */ export function mergeMapTo>( innerObservable: O, @@ -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 1425234c6d..6e1e37c9ce 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: diff --git a/src/internal/operators/mergeWith.ts b/src/internal/operators/mergeWith.ts index 8046e141e2..b0c81426fb 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 8a8058f862..bef78d1c50 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 8f0b23c038..1e4e87e5e9 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'; * }); diff --git a/src/internal/operators/onErrorResumeNext.ts b/src/internal/operators/onErrorResumeNext.ts index 9fdfcb1348..18ccd07ee6 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 @@ -69,13 +74,13 @@ export function onErrorResumeNext( * // 1 * // 2 * // 3 - * // "that's it!" + * // 'that's it!' * ``` * * @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 b040463563..59b68180f7 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)); * ``` * diff --git a/src/internal/operators/partition.ts b/src/internal/operators/partition.ts index 6fa9354cdd..9b02a0c0b9 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 aa1dc49a40..8825089d38 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)); * ``` * diff --git a/src/internal/operators/publish.ts b/src/internal/operators/publish.ts index 7de67d27aa..105cd36729 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. diff --git a/src/internal/operators/publishLast.ts b/src/internal/operators/publishLast.ts index 7cde7f50d5..ded47fb523 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} diff --git a/src/internal/operators/raceWith.ts b/src/internal/operators/raceWith.ts index 3953fa55cf..6e7292982e 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 9ff5de8566..c9bdda0543 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 2fab3f55f8..222a180fca 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 41edff34b8..9e72939e42 100644 --- a/src/internal/operators/repeat.ts +++ b/src/internal/operators/repeat.ts @@ -45,28 +45,32 @@ export interface RepeatConfig { * - `repeat({ delay: (count) => timer(count * 1000) })` will repeat forever, but will have a delay that grows by one second for each repetition. * * ## Example + * * Repeat a message stream + * * ```ts * 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, take, repeat } 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 7253ade1cd..dadc7bb406 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'); * - * source.pipe(repeatWhen(() => documentClick$) - * ).subscribe(data => console.log(data)) + * const result = source.pipe(repeatWhen(() => documentClick$)); + * + * 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 554528c225..9b5012cfcf 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 diff --git a/src/internal/operators/retryWhen.ts b/src/internal/operators/retryWhen.ts index 5d5f15c547..042ef3c7ce 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 diff --git a/src/internal/operators/sample.ts b/src/internal/operators/sample.ts index 7ce877f917..446bdccd3d 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)); * ``` * diff --git a/src/internal/operators/sampleTime.ts b/src/internal/operators/sampleTime.ts index 0a5dda2830..6558fa03ab 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 1242994386..e97e967e59 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 9d1d7be642..e9d035094f 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 433649149b..cbed063b80 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,8 +137,7 @@ export function share(options: ShareConfig): MonoTypeOperatorFunction; * // subscription 3: 2 * ``` * - * @see {@link api/index/function/interval} - * @see {@link map} + * @see {@link shareReplay} * * @return A function that returns an Observable that mirrors the source. */ diff --git a/src/internal/operators/shareReplay.ts b/src/internal/operators/shareReplay.ts index 49c59e9314..f99215f9cd 100644 --- a/src/internal/operators/shareReplay.ts +++ b/src/internal/operators/shareReplay.ts @@ -38,43 +38,71 @@ 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, take, shareReplay } 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 +119,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 +166,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 e4151a6aa1..a17dfefae0 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. diff --git a/src/internal/operators/skip.ts b/src/internal/operators/skip.ts index 02f8fc0930..76e3eff2df 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 20e652920d..97d410859e 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)); diff --git a/src/internal/operators/skipUntil.ts b/src/internal/operators/skipUntil.ts index b17bdb96b8..c693f83ede 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 diff --git a/src/internal/operators/skipWhile.ts b/src/internal/operators/skipWhile.ts index 18367c15cc..e9323fe8bd 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 { from, skipWhile } from 'rxjs'; * * const source = from(['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 { from, skipWhile } from 'rxjs'; * * const source = from([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} diff --git a/src/internal/operators/startWith.ts b/src/internal/operators/startWith.ts index b639a16f7f..8c11ddb52b 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 0e90593221..17240d0488 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 9e854dda6a..69e9cbb3a7 100644 --- a/src/internal/operators/switchAll.ts +++ b/src/internal/operators/switchAll.ts @@ -19,19 +19,19 @@ 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() - * ).subscribe(x => console.log(x)); + * source + * .pipe(switchAll()) + * .subscribe(x => console.log(x)); * * // Output * // click @@ -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 3c8cd1fa3f..37ece8b2d2 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 diff --git a/src/internal/operators/switchMapTo.ts b/src/internal/operators/switchMapTo.ts index 5025d4ce2b..1436204f70 100644 --- a/src/internal/operators/switchMapTo.ts +++ b/src/internal/operators/switchMapTo.ts @@ -3,12 +3,12 @@ import { ObservableInput, OperatorFunction, ObservedValueOf } from '../types'; import { isFunction } from '../util/isFunction'; /* tslint:disable:max-line-length */ -export function switchMapTo>(observable: O): OperatorFunction>; +export function switchMapTo>(observable: O): OperatorFunction>; /** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */ export function switchMapTo>( observable: O, resultSelector: undefined -): OperatorFunction>; +): OperatorFunction>; /** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */ export function switchMapTo>( observable: O, @@ -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 e8bc9ba931..35e5181b24 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)); diff --git a/src/internal/operators/takeLast.ts b/src/internal/operators/takeLast.ts index 3e3697ce60..c10828db13 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)); diff --git a/src/internal/operators/takeUntil.ts b/src/internal/operators/takeUntil.ts index 3c594a0420..7e37cc52c2 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 969256168e..155e963689 100644 --- a/src/internal/operators/takeWhile.ts +++ b/src/internal/operators/takeWhile.ts @@ -27,12 +27,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)); * ``` diff --git a/src/internal/operators/tap.ts b/src/internal/operators/tap.ts index 364d4ca3eb..890d9bcbca 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); * ``` diff --git a/src/internal/operators/throttle.ts b/src/internal/operators/throttle.ts index 74a2285534..28e16ffd93 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)); * ``` * diff --git a/src/internal/operators/throttleTime.ts b/src/internal/operators/throttleTime.ts index 8dc17e6f9f..54461bf6a1 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 b7ab366598..5075d66446 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); + * } * }); * ``` * diff --git a/src/internal/operators/timeInterval.ts b/src/internal/operators/timeInterval.ts index 8fa26950b6..9becdc79dd 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 44657c8269..e8a03ae398 100644 --- a/src/internal/operators/timeout.ts +++ b/src/internal/operators/timeout.ts @@ -74,14 +74,14 @@ 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 */ @@ -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 0870d8013a..7f9078f301 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 efecad7fb2..bb388de0de 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 bab880281f..8c60aced2b 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 3be79a09cf..c379ba4c2d 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} diff --git a/src/internal/operators/windowCount.ts b/src/internal/operators/windowCount.ts index d01e09335e..65df25bd73 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)); * ``` diff --git a/src/internal/operators/windowTime.ts b/src/internal/operators/windowTime.ts index 4301e616ad..7c119b8b43 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)); * ``` diff --git a/src/internal/operators/windowToggle.ts b/src/internal/operators/windowToggle.ts index ce1c3958b8..eb81cb5124 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); diff --git a/src/internal/operators/windowWhen.ts b/src/internal/operators/windowWhen.ts index c8ae1556de..3d8161af5b 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)); * ``` diff --git a/src/internal/operators/withLatestFrom.ts b/src/internal/operators/withLatestFrom.ts index 9e4bc97a17..763410478d 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);