Created
November 30, 2021 12:18
-
-
Save zalito12/5f35fd8200d568652b293198004ba69e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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