Skip to content

Instantly share code, notes, and snippets.

@mattpodwysocki
Last active September 23, 2015 17:22
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 mattpodwysocki/359ee9976b0d7a9f602c to your computer and use it in GitHub Desktop.
Save mattpodwysocki/359ee9976b0d7a9f602c to your computer and use it in GitHub Desktop.
// By default not ref counted
const source = fetchObservable('someurl');
// Everyone gets their own request
const disp1 = source.subscribe(x => console.log(`First ${x}`));
const disp2 = source.subscribe(x => console.log(`Second ${x}`));
// Disposing does not affect one another
disp1.dispose();
disp2.dispose();
// Adding ref counting
const refSource = fetchObservable('someurl').share();
// Add two references
const refDisp1 = refSource.subscribe(x => console.log(`First ${x}`));
const refDisp2 = refSource.subscribe(x => console.log(`Second ${x}`));
// Once the ref count hits zero, the whole operation is cancelled
refDisp1.dispose();
refDisp2.dispose();
// To mimic Promises, we could use AsyncSubject which acts as a thenable
const subject = new Rx.AsyncSubject();
// Will not resolve until both onNext and onCompleted have been called (or onError)
subject.onNext(42);
subject.onCompleted();
subject.subscribe(x => `From AsyncSubject ${x}`)
@jakearchibald
Copy link

Assuming cancelUnderlyingFetch() cancelled the underlying fetch, when would fetchObservable's implementation call this (and how)?

@mattpodwysocki
Copy link
Author

@jakearchibald if it cancelled, then it would immediately call onCompleted which then calls dispose and not allow anything new on that stream as per the AutoDetachObserver

@mattpodwysocki
Copy link
Author

And the AbstractObserver is also the gatekeeper to prevent any re-entry which is wrapped by the AutoDetachObserver

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment