[RxJS] Subject basic

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 Observersw subscribe it.

First time I read 

 implements both Observer and Observable types

I was quite confused. 

 

As a Observable:

复制代码
var subject = new Rx.Subject();
var subscription = subject.subscribe(
   function onNext(x) { console.log('onNext: ' + x); },
   function onError(e) { console.log('onError: ' + e.message); },
   function onCompleted() { console.log('onCompleted'); }
);
subject.onNext('Our message #1');
subject.onNext('Our message #2');

/*
"onNext: Our message #1"
"onNext: Our message #2"
*/
复制代码

Every time we call onNext() message to yield the value.

 

As a Observer, so we use 'source' to sebscribe 'subject', then subscribe 'subject' again to get the side effect

复制代码
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); },
   function onError(e) { console.log('onError: ' + e.message); },
   function onCompleted() { console.log('onCompleted'); }
);
setTimeout(function() {
   subject.onCompleted();
}, 1000);

/*
"onNext: Interval message #0"
"onNext: Interval message #1"
"onNext: Interval message #2"
"onCompleted"
*/
复制代码
posted @   Zhentiw  阅读(236)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示