From 0f8c929406a8da7eb3e6bc8e6a870c9a025144b9 Mon Sep 17 00:00:00 2001 From: Jason Weinzierl Date: Sat, 16 Nov 2024 11:00:37 -0600 Subject: [PATCH] docs(no-async-subscribe): additional explanation --- docs/rules/no-async-subscribe.md | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/docs/rules/no-async-subscribe.md b/docs/rules/no-async-subscribe.md index c19cf915..08685f14 100644 --- a/docs/rules/no-async-subscribe.md +++ b/docs/rules/no-async-subscribe.md @@ -7,6 +7,9 @@ This rule effects failures if async functions are passed to `subscribe`. +Developers are encouraged to avoid race conditions +by instead using RxJS operators which can handle both Promises and Observables +(e.g. `concatMap`, `switchMap`, `mergeMap`, `exhaustMap`). ## Rule details @@ -14,16 +17,26 @@ Examples of **incorrect** code for this rule: ```ts import { of } from "rxjs"; -of(42).subscribe(async () => console.log(value)); + +of(42).subscribe(async value => { + const data1 = await fetch(`https://api.some.com/things/${value}`); + const data2 = await fetch(`https://api.some.com/things/${data1.id}`); + console.log(data2); +}); ``` Examples of **correct** code for this rule: ```ts import { of } from "rxjs"; -of(42).subscribe(() => console.log(value)); + +of(42).pipe( + switchMap(value => fetch(`http://api.some.com/things/${value}`)), + switchMap(data1 => fetch(`http://api.some.com/things/${data1.id}`)), +).subscribe(data2 => console.log(data2)); ``` ## Further reading - [Why does this rule exist?](https://stackoverflow.com/q/71559135) +- [Higher-order Observables](https://rxjs.dev/guide/higher-order-observables)