Skip to content

Instantly share code, notes, and snippets.

@zalito12
Created November 30, 2021 12:18
Show Gist options
  • Save zalito12/5f35fd8200d568652b293198004ba69e to your computer and use it in GitHub Desktop.
Save zalito12/5f35fd8200d568652b293198004ba69e to your computer and use it in GitHub Desktop.
import { combineLatest, concat, interval, Observable } from 'rxjs';
import { debounceTime, map, skip, switchMap, take, tap } from 'rxjs/operators';
export interface ShowMessage {
showMessage: boolean;
}
export class ObservableUtils {
/**
* Generate an observable that will emit twice, instantly and after delay. Second time the show message will be set to false.
*/
public static showAndHide<T>(observable: Observable<T>, control: ShowMessage, delay: number): Observable<T> {
return combineLatest([observable, observable.pipe(debounceTime(delay))]).pipe(
map(([value, delayedValue]) => {
control.showMessage = true;
if (value === delayedValue || !value) {
control.showMessage = false;
}
return value;
})
);
}
/**
* Generate a new interval observable that will be reset when observable param emits
* @param resetObservable observable that will reset interval every time it emits
* @param intervalMillis interval time in milliseconds
* @returns An interval observable
*/
public static intervalWithReset(resetObservable: Observable<any>, intervalMillis: number): Observable<number> {
return resetObservable.pipe(
switchMap(() => {
// SwitchMap generates new interval each time resetObservable emits and dropps previous inner observable
return interval(intervalMillis);
})
);
}
/**
* Generates an observable that will emit first top values and next emisions will be delayed with debounceTime
* @param observable observable who will emit the values
* @param dueTime delay time. Emisions between delays will be dropped
* @param top number of items to be emited without delay
* @returns An observable with some pipes
*/
public static debounceAfterTop<T>(observable: Observable<T>, dueTime: number, top: number = 1): Observable<T> {
return concat(observable.pipe(take(top)), observable.pipe(skip(top), debounceTime(dueTime)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment