Skip to content

Instantly share code, notes, and snippets.

@yjaaidi
Created September 2, 2022 18:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yjaaidi/be763bbc3c96c46394c4b115aa6cb770 to your computer and use it in GitHub Desktop.
Save yjaaidi/be763bbc3c96c46394c4b115aa6cb770 to your computer and use it in GitHub Desktop.
switchMapOnNext rxjs operator
import * as rx from 'rxjs';
const delays = [3000, 2000, 500];
const switchMapOnNext = (project) => (source) => {
return new rx.Observable((observer) => {
let previousSubs = new rx.Subscription();
const subscription = source.subscribe((value) => {
const result$ = project(value);
const currentPreviousSubs = previousSubs;
const sub = result$.subscribe((result) => {
currentPreviousSubs.unsubscribe();
observer.next(result);
});
previousSubs = new rx.Subscription();
previousSubs.add(currentPreviousSubs);
previousSubs.add(sub);
});
return () => subscription.unsubscribe();
});
};
rx.timer(0, 1000)
.pipe(switchMapOnNext((i) => rx.of(i).pipe(rx.delay(delays[i] ?? 0))))
.subscribe(console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment