Skip to content

Commit a5e51b1

Browse files
docs(no-async-subscribe): additional explanation (#26)
I frequently see `no-async-subscribe` triggered by developers new to RxJS trying to use Promises. Additional explanation of this rule is necessary.
1 parent 2d09b5e commit a5e51b1

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

docs/rules/no-async-subscribe.md

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,23 +7,36 @@
77
<!-- end auto-generated rule header -->
88

99
This rule effects failures if async functions are passed to `subscribe`.
10+
Developers are encouraged to avoid race conditions
11+
by instead using RxJS operators which can handle both Promises and Observables
12+
(e.g. `concatMap`, `switchMap`, `mergeMap`, `exhaustMap`).
1013

1114
## Rule details
1215

1316
Examples of **incorrect** code for this rule:
1417

1518
```ts
1619
import { of } from "rxjs";
17-
of(42).subscribe(async () => console.log(value));
20+
21+
of(42).subscribe(async value => {
22+
const data1 = await fetch(`https://api.some.com/things/${value}`);
23+
const data2 = await fetch(`https://api.some.com/things/${data1.id}`);
24+
console.log(data2);
25+
});
1826
```
1927

2028
Examples of **correct** code for this rule:
2129

2230
```ts
2331
import { of } from "rxjs";
24-
of(42).subscribe(() => console.log(value));
32+
33+
of(42).pipe(
34+
switchMap(value => fetch(`http://api.some.com/things/${value}`)),
35+
switchMap(data1 => fetch(`http://api.some.com/things/${data1.id}`)),
36+
).subscribe(data2 => console.log(data2));
2537
```
2638

2739
## Further reading
2840

2941
- [Why does this rule exist?](https://stackoverflow.com/q/71559135)
42+
- [Higher-order Observables](https://rxjs.dev/guide/higher-order-observables)

0 commit comments

Comments
 (0)