A set of tools to avoid race conditions in RxJS subscriptions.
The usual way to avoid race conditions in RxJS is to use switchMap
.
import { HttpCLient, Params } from '...';
import { Subject, switchMap } from 'rxjs';
class TestClass {
private load$ = new Subject<Params>();
constructor(protected readonly http: HttpCLient) {
this._watchLoad$();
}
private _watchLoad$() {
this.load$.pipe(switchMap((params) => this.http.get('path', { params }))).subscribe();
}
load(params: Params) {
this.load$.next(params);
}
}
This method is quite cumbersome and doesn't prevent unnecessary calls. This library allows to manage this problem in a simpler way, avoiding unnecessary calls.
Using NPM
npm install --save @kuoki/race-condition
Using Yarn
yarn add @kuoki/race-condition
Dependencies
import { HttpCLient, Params } from '...';
import { RaceConditionFreeSubscription } from '@kuoki/race-condition';
class TestClass {
protected subscriptions = new RaceConditionFreeSubscription();
constructor(protected readonly http: HttpCLient) {}
noSafeLoad(params: Params) {
this.http.get('path', { params }).subscribe();
}
load(params: Params) {
const _load = () => this.http.get('path', { params }).subscribe();
this.subscriptions.add('load', _load, params);
}
}
This class is very useful when calling functions that return an Observable with arguments, mainly avoiding memory leaks and race conditions due to slow loads.
noSafeLoad({ a: '0' }); // ----------(a|)
noSafeLoad({ a: '1' }); // ^--(a|)
In this example, the user wants to display the data filtering by { a: 0 }
, but right after filter again by using { a: 1 }
. The second call resolves faster, so it is displayed first, but when the first call resolves it replaces the values that were displayed with its own, and obviously these are not the results that the user expected to get. Using this method we solve this problem through the following behavior:
load({ a: '0' }); // -----(a|)
load({ a: '0' }); // ^
load({ a: '0' }); // --|
load({ a: '1' }); // ^----(a|)
load({ a: '0' }); // -----(a|)
load({ a: '0' }); // ^----(a|)
this.subscriptions.get('load'); // 'load' Subscription
this.subscriptions.get('noKey'); // undefined
this.subscriptions.unsubscribe('load'); // unsubscribes 'load' Subscription
this.subscriptions.unsubscribe(); // unsubscribes all subscriptions
This decorator allows you to simplify the way you handle race conditions by applying it in a method that returns a subscription. This also allows for cleaner code and to use other common decorators like @debounce
.
import { HttpCLient, Params } from '...';
import { RaceConditionFree } from '@kuoki/race-condition';
import { Subscription } from 'rxjs';
class TestClass {
constructor(protected readonly http: HttpCLient) {}
@RaceConditionFree()
load(params: Params): Subscription {
return this.http.get('path', { params }).subscribe();
}
}
Generated using TypeDoc