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

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.

主站蜘蛛池模板: 镇巴县| 安达市| 札达县| 鲁山县| 蓬溪县| 华宁县| 沂水县| 郯城县| 安徽省| 将乐县| 什邡市| 凯里市| 宣武区| 临夏市| 洪湖市| 彰化市| 观塘区| 文登市| 佛山市| 永新县| 息烽县| 长汀县| 台北县| 盐边县| 监利县| 屏山县| 沅陵县| 阿坝| 盈江县| 宣武区| 京山县| 石门县| 兴国县| 二手房| 赤水市| 宜宾县| 东城区| 云龙县| 庄浪县| 绥阳县| 云南省|