例如,如果给定一个带有操作的通道和另一个带有数据的通道,如何编写一个go
块,它将对数据通道上的最后一个值应用该操作?
(go-loop []
(let [op (<! op-ch)
data (<! data-ch)]
(put! result-ch (op data))))
显然这不起作用,因为它需要两个频道具有相同的频率。
答案 0 :(得分:1)
使用alts!
你可以完成你想要的任务。
下面显示的with-latest-from
实现了与RxJS的withLatestFrom
相同的行为(我认为:P)。
(require '[clojure.core.async :as async])
(def op-ch (async/chan))
(def data-ch (async/chan))
(defn with-latest-from [chs f]
(let [result-ch (async/chan)
latest (vec (repeat (count chs) nil))
index (into {} (map vector chs (range)))]
(async/go-loop [latest latest]
(let [[value ch] (async/alts! chs)
latest (assoc latest (index ch) value)]
(when-not (some nil? latest)
(async/put! result-ch (apply f latest)))
(when value (recur latest))))
result-ch))
(def result-ch (with-latest-from [op-ch data-ch] str))
(async/go-loop []
(prn (async/<! result-ch))
(recur))
(async/put! op-ch :+)
;= true
(async/put! data-ch 1)
;= true
; ":+1"
(async/put! data-ch 2)
;= true
; ":+2"
(async/put! op-ch :-)
;= true
; ":-2"
答案 1 :(得分:1)
<div ng-controller="MoviesCtrl">
<ul>
<li ng-repeat="movie in movies | searchMovies:filterByGenres">
{{ movie.name }} {{ movie.genre }}
</li>
</ul>
</div>
有一个:priority true
选项。
总是返回某个通道中最新看到的值的表达式如下所示:
alts!
未经测试,可能效率不高((def in-chan (chan))
(def mem (chan))
(go (let [[ch value] (alts! [in-chan mem] :priority true)]
(take! mem) ;; clear mem (take! is non-blocking)
(>! mem value) ;; put the new (or old) value in the mem
value ;; return a chan with the value in
变量可能更好)。 volatile
- 块返回一个只包含值的频道,但这个想法可以扩展到一些&#34; memoized&#34;信道。