走进rxjs的世界 - 万物皆流 - Everything is a stream

118 阅读1分钟

一些使用案例

  1. 轻易实现让服务器retry客户端发起的HTTP调用:
return this.http.get('/api/v1/tasks.json')
      .retry(5)
      .map( res => res.json());
      ...
  1. 每隔10秒钟,轮询一次
pollTasks() {
     return Observable.interval(10000)
      .flatMapLatest(() => http.get('/api/v1/tasks.json'))
      .map(res => res.json())
    }
    // caller can do subscription and store it as a handle:
    let tasksSubscription =
      pollTasks()
        .subscribe( data => this.payload = data);
    // turn it off at a later time
    tasksSubscription.unsubscribe();

the pollTasks() method emits a call every 10 seconds, which triggers the call inside of flatMapLatest – we’re basically ignoring the result of that event, and using it to trigger the http.get method to fetch our data. We’ll map it into JSON each time.

pollTasks方法返回一个Observable对象,封装了一个10秒间隔的周期性调用,调用内部会执行http操作读取tasks.json文件,将结果以json格式返回。

The caller of our pollTasks() method just gets an observable, which is emitting content every 10 seconds.

调用pollTasks方法,只会返回一个Observable对象,这个Observable对象subscribe之后,会每隔10秒产生内容。调用unsubscribe关闭。

Also the flatMapLatest call is really interesting – any calls generated by previous events are canceled, including their in-flight HTTP method calls. Try doing that with a promise!

flagMapLatest是一个强力方法,这里将其当作一种engine使用:所有基于之前发生的事件触发的调用都会自动被cancel,包括正在进行中的in-flight HTTP调用。很难想象使用promise实现类似的方法,会花费多大的工作量。

参考文献