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

后端 未结 3 1577
梦谈多话
梦谈多话 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:35

    You seem to mean that modifiedSince is part of the state you carry, so it should appear in the scan. Why don-t you move the action in do into the scan too?. Your seed would then be {modifiedSince: null, itemArray: []}.

    Errr, I just thought that this might not work, as you need to feed modifiedSince back to the fetchItem function which is upstream. Don't you have a cycle here? That means you would have to use a subject to break that cycle. Alternatively you can try to keep modifiedSince encapsulated in a closure. Something like

    function pollItems (fetchItems, polling_frequency) {
    var modifiedSince = null;
    var data$ = Rx.Observable.interval(polling_frequency)
      .startWith('run right away')
      .flatMap(function() { 
        // `fetchItems(modifiedSince)` returns an array of items modified after `modifiedSince`
        return fetchItems(modifiedSince);
      })
      .do(function(item) {
        if(item.updatedAt > modifiedSince) {
          modifiedSince = item.updatedAt;
        }
      })
      .scan(function(previous, current) {
        previous.push(current);
        return previous;
      }, []);
    
    return data$;
    }
    

    I have to run out to celebrate the new year, if that does not work, I can give another try later (maybe using the expand operator, the other version of scan).

提交回复
热议问题