rxjs 中的 Observable 和 Subject 有什么区别? [英] What is the difference between Observable and a Subject in rxjs?
问题描述
我正在浏览这个 博客 并阅读有关 Observables 的内容,但无法弄清楚Observable 和 Subject 的区别.
I was going through this blog and reading about Observables and couldn't figure out the difference between the Observable and a Subject.
推荐答案
在流编程中有两个主要接口:Observable 和 Observer.
In stream programming there are two main interfaces: Observable and Observer.
Observable是面向消费者的,可以转化和订阅:
Observable is for the consumer, it can be transformed and subscribed:
observable.map(x => ...).filter(x => ...).subscribe(x => ...)
Observer 是用于提供可观察源的接口:
Observer is the interface which is used to feed an observable source:
observer.next(newItem)
我们可以使用 Observer 创建新的 Observable:
We can create new Observable with an Observer:
var observable = Observable.create(observer => {
observer.next('first');
observer.next('second');
...
});
observable.map(x => ...).filter(x => ...).subscribe(x => ...)
或者,我们可以使用同时实现 Observable 和 Observer 接口的 Subject:
Or, we can use a Subject which implements both the Observable and the Observer interfaces:
var source = new Subject();
source.map(x => ...).filter(x => ...).subscribe(x => ...)
source.next('first')
source.next('second')
这篇关于rxjs 中的 Observable 和 Subject 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!