Skip to content

Commit

Permalink
docs: update operator imports in examples (#6678)
Browse files Browse the repository at this point in the history
* docs: update operator imports in examples

* docs(README.md): update operator imports in examples

* docs: use shorthand version for TypeScript at code markup start

Change from 'typescript' to 'ts' at the beginning of markup code examples, as 'ts' is used in almost every other file.

* refactor: use 'asyncScheduler' instead of 'async' where possible

* docs: fix headings

* docs: fix links and @see links

* docs: unify examples

Use single quotes, fix whitespace issues, delete trailing commas, remove extra parenthesis, convert to arrow functions, update parameters to non-deprecated version of subscribe, fix grammar.

* docs: use map and concatMap instead of mapTo and concatMapTo in examples

* docs: use tap's new callback functions to avoid using defer and finalize

* docs(share): use tap for logging in share example

* docs(dematerialize): fix TS errors in dematerialize example
  • Loading branch information
jakovljevic-mladen committed Jan 4, 2022
1 parent bca49bd commit 888c753
Show file tree
Hide file tree
Showing 130 changed files with 1,406 additions and 1,331 deletions.
24 changes: 19 additions & 5 deletions README.md
Expand Up @@ -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(
Expand All @@ -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(
Expand Down
79 changes: 40 additions & 39 deletions src/internal/Observable.ts
@@ -1,6 +1,3 @@
/**
* @prettier
*/
import { Operator } from './Operator';
import { SafeSubscriber, Subscriber } from './Subscriber';
import { isSubscription, Subscription } from './Subscription';
Expand Down Expand Up @@ -124,8 +121,10 @@ export class Observable<T> implements Subscribable<T> {
* 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';
*
Expand All @@ -148,13 +147,14 @@ export class Observable<T> implements Subscribable<T> {
* .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'
*
Expand All @@ -170,13 +170,14 @@ export class Observable<T> implements Subscribable<T> {
* );
*
* // 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';
*
Expand All @@ -198,14 +199,14 @@ export class Observable<T> implements Subscribable<T> {
* // 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
Expand Down Expand Up @@ -260,36 +261,36 @@ export class Observable<T> implements Subscribable<T> {
* 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
Expand Down Expand Up @@ -419,18 +420,18 @@ export class Observable<T> implements Subscribable<T> {
* @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(
* filter(x => x % 2 === 0),
* map(x => x + x),
* scan((acc, x) => acc + x)
* )
* .subscribe(x => console.log(x))
* .subscribe(x => console.log(x));
* ```
*/
pipe(...operations: OperatorFunction<any, any>[]): Observable<any> {
Expand Down
68 changes: 43 additions & 25 deletions src/internal/ajax/ajax.ts
Expand Up @@ -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 => {
Expand All @@ -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);
Expand Down Expand Up @@ -173,43 +173,53 @@ function ajaxGetJSON<T>(url: string, headers?: Record<string, string>): 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);
* return of(error);
* })
* );
*
* 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',
Expand All @@ -229,22 +239,30 @@ function ajaxGetJSON<T>(url: string, headers?: Record<string, string>): 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);
* return of(error);
* })
* );
*
* obs$.subscribe({
* next: value => console.log(value),
* error: err => console.log(err)
* });
* ```
*/
export const ajax: AjaxCreationMethod = (() => {
Expand Down
8 changes: 4 additions & 4 deletions src/internal/firstValueFrom.ts
Expand Up @@ -28,24 +28,24 @@ export function firstValueFrom<T>(source: Observable<T>): Promise<T>;
* 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';
*
* 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}
Expand Down
11 changes: 5 additions & 6 deletions src/internal/lastValueFrom.ts
Expand Up @@ -26,25 +26,24 @@ export function lastValueFrom<T>(source: Observable<T>): Promise<T>;
* 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}
Expand Down

0 comments on commit 888c753

Please sign in to comment.