Tiven Wang
Wang Tiven March 21, 2018
425 favorite favorites
bookmark bookmark
share share

Observables provide support for passing messages between publishers and subscribers in your application. Observables offer significant benefits over other techniques for event handling, asynchronous programming, and handling multiple values.[1.]

关于 RxJS 框架的介绍和应用可以参考另外几篇文章

Basic

我们来简单看一下 Observable 基本流程

Pattern: Observable => Subscriber => Subscription

const timer = new Observable((observer) => {
  let interval = setInterval(()=>
    observer.next(new Date(), 1000)
  );
  return {
    unsubscribe() {
      clearInterval(interval);
    }
  };
});
const timerSubscription = timer.subscribe({
  next(t) { console.log('Current time: ', t); },
  error(msg) { console.log('Error Getting Time: ', msg); }
});

// Stop listening for location after 10 seconds
setTimeout(() => { timerSubscription.unsubscribe(); }, 10000);

Observables in Angular

Angular 为他的很多常用异步操作都实现了 Observable , 这包括

  • EventEmitter class extends Observable
  • The HTTP module uses observables to handle AJAX requests and responses.
  • The Router and Forms modules use observables to listen for and respond to user-input events.

References

Similar Posts

Comments

Back to Top