Skip to content

Instantly share code, notes, and snippets.

@QuentinRoy
Created October 20, 2017 02:36
Show Gist options
  • Save QuentinRoy/09f3aafaa5c6d9be132855735e08a051 to your computer and use it in GitHub Desktop.
Save QuentinRoy/09f3aafaa5c6d9be132855735e08a051 to your computer and use it in GitHub Desktop.
Transform a node stream into an rxjs Observer
import { Observable } from 'rxjs';
// Adapted from https://github.com/Reactive-Extensions/rx-node/blob/87589c07be626c32c842bdafa782fca5924e749c/index.js#L52
export default function fromStream(stream, finishEventName = 'end', dataEventName = 'data') {
stream.pause();
return new Observable((observer) => {
function dataHandler(data) {
observer.next(data);
}
function errorHandler(err) {
observer.error(err);
}
function endHandler() {
observer.complete();
}
stream.addListener(dataEventName, dataHandler);
stream.addListener('error', errorHandler);
stream.addListener(finishEventName, endHandler);
stream.resume();
return () => {
stream.removeListener(dataEventName, dataHandler);
stream.removeListener('error', errorHandler);
stream.removeListener(finishEventName, endHandler);
};
}).share();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment