// @todo potentially import this util from `sanity` import { finalize, merge, Observable, share, tap, type MonoTypeOperatorFunction, type ShareConfig, } from 'rxjs' export type ShareReplayLatestConfig = ShareConfig & {predicate: (value: T) => boolean} /** * A variant of share that takes a predicate function to determine which value to replay to new subscribers * @param predicate - Predicate function to determine which value to replay */ export function shareReplayLatest(predicate: (value: T) => boolean): MonoTypeOperatorFunction /** * A variant of share that takes a predicate function to determine which value to replay to new subscribers * @param config - ShareConfig with additional predicate function */ export function shareReplayLatest( config: ShareReplayLatestConfig, ): MonoTypeOperatorFunction /** * A variant of share that takes a predicate function to determine which value to replay to new subscribers * @param configOrPredicate - Predicate function to determine which value to replay * @param config - Optional ShareConfig */ export function shareReplayLatest( configOrPredicate: ShareReplayLatestConfig | ShareReplayLatestConfig['predicate'], config?: ShareConfig, ): MonoTypeOperatorFunction { return _shareReplayLatest( typeof configOrPredicate === 'function' ? {predicate: configOrPredicate, ...config} : configOrPredicate, ) } function _shareReplayLatest(config: ShareReplayLatestConfig): MonoTypeOperatorFunction { return (source: Observable) => { let latest: T | undefined let emitted = false // eslint-disable-next-line @typescript-eslint/no-unused-vars const {predicate, ...shareConfig} = config const wrapped = source.pipe( tap((value) => { if (config.predicate(value)) { emitted = true latest = value } }), finalize(() => { emitted = false latest = undefined }), share(shareConfig), ) const emitLatest = new Observable((subscriber) => { if (emitted) { subscriber.next( // this cast is safe because of the emitted check which asserts that we got T from the source latest as T, ) } subscriber.complete() }) return merge(wrapped, emitLatest) } }