Node.js 스트림 vs. Observable
Observable 에 대해 배운 후 Node.js 스트림 과 매우 유사하다는 것을 알게되었습니다 . 둘 다 새 데이터가 도착하거나 오류가 발생하거나 더 이상 데이터 (EOF)가 없을 때마다 소비자에게 알리는 메커니즘이 있습니다.
나는 둘 사이의 개념적 / 기능적 차이점에 대해 배우고 싶습니다. 감사!
두 Observables은 과 Node.js를의 스트림은 같은 근본적인 문제를 해결 할 수 있습니다 : 비동기 값의 시퀀스를 처리합니다. 이 둘의 주요 차이점은 외모에 동기를 부여한 맥락과 관련이 있다고 생각합니다. 이러한 컨텍스트는 용어 및 API에 반영됩니다.
온 Observable 인의 면 당신은 소개하고 반응 프로그래밍 모델이 ECMA 스크립트의 확장이있다. 그리고의 미니멀하고 구성 가능한 개념으로 가치 창출과 비동기 성 사이의 격차를 메우려 Observer
고 Observable
합니다.
node.js 및 Streams 측에서 네트워크 스트림 및 로컬 파일의 비동기 및 성능 처리를위한 인터페이스를 만들고 싶었습니다. 그 초기 문맥에서 용어의 도출은 당신이 얻을 pipe
, chunk
, encoding
, flush
, Duplex
, Buffer
, 등이 균일 한대로 아니기 때문에 당신이 작성 것들을 몇 가지 능력을 상실 특정 사용 사례에 대한 명시 적 지원을 제공하는 실용적인 접근 방식을 가짐으로써. 예를 들어, 사용 push
A의 Readable
스트림 write
에 Writable
개념적으로, 당신은 같은 일을하고있다, 비록 : 값을 게시합니다.
그래서, 실제로, 당신은 개념을 보면, 당신이 옵션을 사용하는 경우 { objectMode: true }
, 당신은 일치시킬 수 있습니다 Observable
와 Readable
스트림과 Observer
와 Writable
스트림입니다. 두 모델간에 간단한 어댑터를 만들 수도 있습니다.
var Readable = require('stream').Readable;
var Writable = require('stream').Writable;
var util = require('util');
var Observable = function(subscriber) {
this.subscribe = subscriber;
}
var Subscription = function(unsubscribe) {
this.unsubscribe = unsubscribe;
}
Observable.fromReadable = function(readable) {
return new Observable(function(observer) {
function nop() {};
var nextFn = observer.next ? observer.next.bind(observer) : nop;
var returnFn = observer.return ? observer.return.bind(observer) : nop;
var throwFn = observer.throw ? observer.throw.bind(observer) : nop;
readable.on('data', nextFn);
readable.on('end', returnFn);
readable.on('error', throwFn);
return new Subscription(function() {
readable.removeListener('data', nextFn);
readable.removeListener('end', returnFn);
readable.removeListener('error', throwFn);
});
});
}
var Observer = function(handlers) {
function nop() {};
this.next = handlers.next || nop;
this.return = handlers.return || nop;
this.throw = handlers.throw || nop;
}
Observer.fromWritable = function(writable, shouldEnd, throwFn) {
return new Observer({
next: writable.write.bind(writable),
return: shouldEnd ? writable.end.bind(writable) : function() {},
throw: throwFn
});
}
당신은 내가 몇 가지 이름을 변경하고의 간단한 개념을 사용하는 것으로 나타났습니다 수 Observer
및 Subscription
수행 reponsibilities의 과부하 방지하기 위해, 여기에서 소개, Observables은 에서를 Generator
. 기본적으로를 Subscription
사용하면 Observable
. 어쨌든 위의 코드를 사용하면 pipe
.
Observable.fromReadable(process.stdin).subscribe(Observer.fromWritable(process.stdout));
Compared with process.stdin.pipe(process.stdout)
, what you have is a way to combine, filter, and transform streams that also works for any other sequence of data. You can achieve it with Readable
, Transform
, and Writable
streams but the API favors subclassing instead of chaining Readable
s and applying functions. On the Observable
model, For example, transforming values corresponds to applying a transformer function to the stream. It does not require a new subtype of Transform
.
Observable.just = function(/*... arguments*/) {
var values = arguments;
return new Observable(function(observer) {
[].forEach.call(values, function(value) {
observer.next(value);
});
observer.return();
return new Subscription(function() {});
});
};
Observable.prototype.transform = function(transformer) {
var source = this;
return new Observable(function(observer) {
return source.subscribe({
next: function(v) {
observer.next(transformer(v));
},
return: observer.return.bind(observer),
throw: observer.throw.bind(observer)
});
});
};
Observable.just(1, 2, 3, 4, 5).transform(JSON.stringify)
.subscribe(Observer.fromWritable(process.stdout))
The conclusion? It's easy to introduce the reactive model and the Observable
concept anywhere. It's harder to implement an entire library around that concept. All those little functions need to work together consistently. After all, the ReactiveX project is still going at it. But if you really need to send the file content to the client, deal with encoding, and zip it then the support it's there, in NodeJS, and it works pretty well.
참고URL : https://stackoverflow.com/questions/30423413/node-js-streams-vs-observables
'program story' 카테고리의 다른 글
전화 번호 [libphonenumber]에서 코드 국가 추출 (0) | 2020.11.02 |
---|---|
TypeScript의 개인 "함수" (0) | 2020.11.02 |
Angular2 동적 변경 CSS 속성 (0) | 2020.11.02 |
Python의 임의의 임의성 (0) | 2020.11.02 |
MSBuild 스크립트 및 VS2010 게시는 Web.config 변환 적용 (0) | 2020.11.02 |