Hands-On Reactive Programming with Clojure
上QQ阅读APP看书,第一时间看更新

Sliding buffer

A drawback of dropping buffers is that we might not be processing the latest items at a given time. For the times where processing the latest information is a must, we can use a sliding buffer:

    (def result (chan (async/sliding-buffer 2)))
    (go-loop []
      (<! (async/timeout 1000))
      (when-let [x (<! result)]
        (prn "Got value: " x)
        (recur)))
    
    (go  (doseq [n (range 5)]
           (>! result n))
         (prn "Done putting values!")
         (async/close! result))
    
    ;; "Done putting values!"
    ;; "Got value: " 3
    ;; "Got value: " 4  

As before, we only get two values, but they are the latest ones that have been produced by the go loop.

When the limit of the sliding buffer is overrun, core.async drops the oldest items to make room for the newest ones. I end up using this buffering strategy most of the time.