typescript - Are RxJS observables different to observables of other languages?
问题描述
I want to move data from one place, to another and consider to use an Observable. I know observables from other languages, but somehow I find them very confusing. Given is the example below from a tutorial:
const foo$ = new Observable(subscriber => {
subscriber.next(42);
subscriber.next(43);
});
Why does the definition of foo = ...
contain the value(s)? If foo would be the observable that can be subscribed to, how are the values coming in dynamically? Why is this called like this? Shouldn't it be triggered like this:
const foo$ = new Observable();
foo.subscribe((data) => console.log(data));
foo.sendSomeData(3);
In my case I want to create an observable which one consumer subscribes to, and the other source simply pushes data.
解决方案
What you want is a subject or a behavior subject. A subject is both an observable and an observer so that it exposes it's next methods. The difference between the two is that a behavior subject stores the previously emitted value and new subscribers get that value on subscribing. Subscribers to a subject get a value the next time the next method is called.
const { Subject } = rxjs;
const obs$ = new Subject();
obs$.subscribe(val => { console.log(val); });
obs$.next('Hello');
setTimeout(() => { obs$.next('Later'); }, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.6.2/rxjs.umd.min.js" integrity="sha512-kN8bAZFoIra6Z7dDPNMD3efoGLn7QpOZgBcNpLwKIoBM5rXLVxt9nPHNo+4WrIsT0RBc/h2sXtN08n1ALxn4yw==" crossorigin="anonymous"></script>
推荐阅读
- normalization - 如何使用 jmespath 从 json 中获取所有名为 ref 的属性?
- python - 我将如何创建一个函数来检查坐标是否在某个地图边界内?
- sql-server-data-tools - 数据库名称作为文件组文件名的一部分
- visual-studio - 在 Visual Studio/msbuild 中,一个目标框架的构建事件如何依赖于另一个?
- linux - kex_exchange_identification:远程主机使用 ~/.ssh/config 文件关闭连接
- tomcat - 如何更改 Tomcat 的 undeployOldVersions 超时?
- c# - 如何在 C# Nest 中将日期值发送到 elasticsearch 聚合查询
- azure - 将 Azure AD 用户与 Gsuite 关联
- haskell - 我们如何在保持类型安全的同时通用地处理关联类型
- docker - ECS Fargate 公共 IP 连接被拒绝