Last active
February 23, 2024 11:01
-
-
Save ezzabuzaid/e89967ad103e699266c4bc9c23c46e6b to your computer and use it in GitHub Desktop.
Extract loading state from observable
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 { | |
Observable, | |
ObservableInput, | |
ReplaySubject, | |
delay, | |
distinctUntilChanged, | |
finalize, | |
from, | |
of, | |
tap, | |
} from 'rxjs'; | |
export function extractLoading<T>( | |
source: ObservableInput<T>, | |
): [Observable<boolean>, Observable<T>] { | |
const loading$ = new ReplaySubject<boolean>(); | |
const tracked$ = new Observable<T>((subscriber) => { | |
loading$.next(true); | |
const subscription = from(source) | |
.pipe( | |
tap(() => loading$.next(false)), | |
finalize(() => loading$.next(false)), | |
) | |
.subscribe(subscriber); | |
return () => { | |
loading$.next(false); | |
loading$.complete(); | |
subscription.unsubscribe(); | |
}; | |
}); | |
return [loading$.pipe(distinctUntilChanged()), tracked$]; | |
} | |
const [loading, source] = extractLoading(fetch('https://jsonplaceholder.typicode.com/posts/1').then( | |
(response) => response.json(), | |
)); | |
// OR with lazy calling | |
const [loading, source] = extractLoading(defer(() => fetch('https://jsonplaceholder.typicode.com/posts/1').then( | |
(response) => response.json(), | |
))); | |
source.subscribe({ | |
next: (value) => { | |
console.log({ source: value }); | |
}, | |
}); | |
loading.subscribe({ | |
next: (value) => { | |
console.log({ loading: value }); | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment