Skip to content

Instantly share code, notes, and snippets.

@sashaaro
Last active October 1, 2021 12:24
Show Gist options
  • Save sashaaro/f0f4e1df5f2804d9e253418b56af1a71 to your computer and use it in GitHub Desktop.
Save sashaaro/f0f4e1df5f2804d9e253418b56af1a71 to your computer and use it in GitHub Desktop.
rxjs operator AsyncLocalStorage
import {AsyncLocalStorage} from "async_hooks";
import {MonoTypeOperatorFunction, Observable, Subscription} from "rxjs";
export function withinContext<T, S = any>(storage: AsyncLocalStorage<S>, store: () => S): MonoTypeOperatorFunction<T> {
return function (source: Observable<T>) {
return new Observable((observer) => {
let sub: Subscription;
storage.run(store(),() => {
sub = source.subscribe(observer);
})
// @ts-ignore
return sub;
});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment