An Observable represents a stream of data.
Observable 代表一个数据流
we just express what we want our code to do, not how to do it
coding过程只是在描述,而不是具体的”coding”
Erik Meijer—the inventor of RxJS—proposed in his paper “Your
Mouse Is a Database.”
对事件流的比喻
there’s no need to create external variables to keep state, which makes the
code self-contained and makes it harder to introduce bugs.There’s no need
to clean up after yourself either, so no chance of introducing memory leaks
by forgetting about unregistering event handlers
自己少些代码,bug引入几率变小
RxJS is push-based, so the source of events (the Observable) will push new values
to the consumer (the Observer), without the consumer requesting the next value.
主动push不是让对方去获取value
和普通观察者模式的区别
• An Observable doesn’t start streaming items until it has at least one
Observer subscribed to it.
没有subscribe的时候,流并不开始
• Like iterators, an Observable can signal when the sequence is completed.
流结束的时候是可以捕获的
Observers listen to Observables. Whenever an event happens in an Observable,
it calls the related method in all of its Observers.
关键词the related method in all of its Observers
function get(url) { |
上面的代码用function包装创建了一个Observable,当得到结果的时候发送值并结束,否则error
但没人subscribe的时候请求是不会执行的,这也解释了RxJS是重点是描述的lazy的
It is only when we call subscribe that the gears start turning
不subscribe流不开始
In an RxJS program, we should strive to have all data in Observables, not just data
that comes from asynchronous sources.
尽可能把所有数据都变成Observables