Created
October 20, 2017 02:36
-
-
Save QuentinRoy/09f3aafaa5c6d9be132855735e08a051 to your computer and use it in GitHub Desktop.
Transform a node stream into an rxjs Observer
This file contains 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 { 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