官术网_书友最值得收藏!

The observer pattern revisited

In Chapter 1, What is Reactive Programming?, we saw a brief overview of the Observer design pattern and a simple implementation of it in Clojure using watches. Here's how we did it:

(def numbers (atom [])) 
 
(defn adder [key ref old-state new-state] 
  (print "Current sum is " (reduce + new-state))) 
 
(add-watch numbers :adder adder)  

In the preceding example, our observable subject is var known as numbers. The observer is the adder watch. When the observable changes, it pushes its changes to the observer synchronously.

Now, contrast this to working with sequences:

(->> [1 2 3 4 5 6] 
     (map inc) 
     (filter even?) 
     (reduce +)) 

This time around, the vector is the subject being observed and the functions processing it can be thought of as the observers. However, this works in a pull-based model. The vector doesn't push any elements down the sequence. Instead, map and friends ask the sequence for more elements. This is a synchronous operation.

Rx makes sequences and other behave like observables so that you can still map, filter, and compose them just as you would compose functions over normal sequences.

主站蜘蛛池模板: 洛阳市| 东安县| 昭觉县| 丽江市| 陆良县| 永修县| 霍林郭勒市| 呈贡县| 泗水县| 林口县| 右玉县| 龙里县| 静安区| 靖远县| 夏津县| 故城县| 常德市| 故城县| 新野县| 明星| 公安县| 麻栗坡县| 修武县| 且末县| 孙吴县| 万山特区| 西吉县| 辽阳县| 霞浦县| 肥城市| 沅江市| 许昌市| 南澳县| 永修县| 辽宁省| 临潭县| 陇川县| 和政县| 社旗县| 原平市| 托里县|