Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Switch using cancellation functions
// For a nested stream, emits the elements of the inner stream contained within the
// most recent outer stream
function switch(stream, n) {
return new Observable(sink => {
let inner = [];
let outer = stream.subscribe({
next(value) {
while (inner.length >= n)
let observer = {
cancel: null,
next: x =>,
error: x => sink.error(x),
complete: _=> { inner.splice(inner.indexOf(this.cancel), 1) },
observer.cancel = value.subscribe(observer);
error: x => sink.error(x),
complete: x => sink.complete(x),
return _=> {
while (inner.length > 0)

This comment has been minimized.

Copy link

boxofrox commented Oct 30, 2015

It took me a long while to realize that inner.shift()() is invoking the unsubscribe function. As a javascript newb, inner.shift().unsubscribe() would be much clearer for me to infer what that second function call does, but this is only an argument if you're striving to promote clarity for newcomers to Observable that like to dig through source with less 'technical debt', if you will.

That said, I think your intent was to call inner.shift().cancel()--which achieves the clarity goal above--since you took the time to stash the unsubscribe callback in observer.cancel, but never pushed anything into inner.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.