how to use the exhaust function from the rxjs library in javascript

To use the exhaust function from the RxJS library in JavaScript, you first need to import it from the library like so:

index.tsx
import { exhaust } from 'rxjs/operators';
42 chars
2 lines

Once you have imported the exhaust function, you can use it to flatten higher-order observables. The exhaust function subscribes to the first observable and ignores any subsequent observables until the first one completes. Only then it will consider the next one.

Here is an example of using exhaust to flatten higher-order observables:

index.tsx
import { of } from 'rxjs';
import { delay, exhaust, map } from 'rxjs/operators';

const source = of(of(1, 2, 3).pipe(delay(2000)), of(4, 5, 6));

source
  .pipe(
    exhaust(),
    map(x => x * 10)
  )
  .subscribe(console.log); //output: 10, 20, 30
250 chars
12 lines

In the above example, we create an observable source that emits two observables: of(1, 2, 3).pipe(delay(2000)) and of(4, 5, 6). We want to flatten the higher-order observables emitted by source using exhaust.

After flattening the observables, we use map to update the emitted value of each observable by multiplying it by 10. The final output emitted from the subscribe method will be 10, 20, 30.

gistlibby LogSnag