Created
September 2, 2022 18:07
-
-
Save yjaaidi/be763bbc3c96c46394c4b115aa6cb770 to your computer and use it in GitHub Desktop.
switchMapOnNext rxjs operator
This file contains hidden or 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 * 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