RxJS, how to poll an API to continuously check for updated records using a dynamic timestamp

后端 未结 3 1565
梦谈多话
梦谈多话 2020-12-30 07:04

I am new to RxJS and I am trying to write an app that will accomplish the following things:

  1. On load, make an AJAX request (faked as fetchItems() f
3条回答
  •  感情败类
    2020-12-30 07:38

    How about this:

    var interval = 1000;
    function fetchItems() {
        return items;
    }
    
    var data$ = Rx.Observable.interval(interval)
      .map(function() { return fetchItems(); })
      .filter(function(x) {return x.lastModified > Date.now() - interval}
      .skip(1)
      .startWith(fetchItems());
    

    That should filter the source only for new items, plus start you off with the full collection. Just write the filter function to be appropriate for your data source.

    Or by passing an argument to fetchItems:

    var interval = 1000;
    function fetchItems(modifiedSince) {
        var retVal = modifiedSince ? items.filter( function(x) {return x.lastModified > modifiedSince}) : items
        return retVal;
    }
    
    var data$ = Rx.Observable.interval(interval)
      .map(function() { return fetchItems(Date.now() - interval); })
      .skip(1)
      .startWith(fetchItems());
    

提交回复
热议问题