RxJS’s Subject Class
A Subject is a type that implements both Observer and Observable types. As an Observer, it can subscribe to Observables, and as an Observable it can produce values and have Observers subscribe to it.
In some scenarios a single Subject can do the work of a combination of Observers and Observables. For example, for making a proxy object between a data source and the Subject’s listeners, we could use this:
| var subject = new Rx.Subject(); |
| var source = Rx.Observable.interval(300) |
| .map(function(v) { return 'Interval message #' + v; }) |
| .take(5); |
| |
| source.subscribe(subject); |
| |
| var subscription = subject.subscribe( |
| function onNext(x) { console.log('onNext: ' + x); }, |
|
Get Reactive Programming with RxJS now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.