分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 教程案例

rxjs——subject和Observable的区别

发布时间:2023-09-06 02:26责任编辑:郭大石关键词:js

一个 Observable 是可以被多个 observer 订阅的,只是每个订阅都是一个新的独立的 Observable execution :

const { Observable } = Rxconst clock$ = Observable.interval(1000).take(3);const observerA = { ?next(v) { ???console.log(‘A next: ‘ + v) ?}}const observerB = { ?next(v) { ???console.log(‘B next: ‘ + v) ?}}clock$.subscribe(observerA) // a Observable executionsetTimeout(() => { ?clock$.subscribe(observerB) // another new Observable execution}, 2000)/* * A next: 0 * A next: 1 * A next: 2 * B next: 0 * B next: 1 * B next: 2 */

如果是同一个 shared Observable execution 的话,B的第一个 emit 的值应该是 2 而不是 0 ,并且只有且仅有一个值 2

const { Observable, Subject } = Rxconst clock$ = Observable.interval(1000).take(3);const observerA = { ?next(v) { ???console.log(‘A next: ‘ + v) ?}}const observerB = { ?next(v) { ???console.log(‘B next: ‘ + v) ?}}const subject = new Subject()subject.subscribe(observerA)clock$.subscribe(subject)setTimeout(() => { ?subject.subscribe(observerB)}, 2000)/* * A next: 0 * A next: 1 * A next: 2 * B next: 2 */

由于 Subject 是多播,也就是每个 observer 都 share 同一个 Observable execution 。
所以B的第一个 emit 的值并且只有一个值是 2 !

大概 Subject 和 Observable 之间一个很重要的区别就是 Subject 是有状态的,它维护观察者列表。另一方面,Observable 真的只是一个函数,它建立了观察本身。

rxjs——subject和Observable的区别

原文地址:https://www.cnblogs.com/panfengde/p/10138899.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved