gpt4 book ai didi

clojure - 如何使用 core.async channel 对 Rx 的 `withLatestFrom` 进行建模?

转载 作者:行者123 更新时间:2023-12-02 16:37:44 25 4
gpt4 key购买 nike

例如,给定一个包含操作的 channel 和另一个包含数据的 channel ,如何编写一个 go block 来将操作应用于数据通道上的最后一个值?

(go-loop []
(let [op (<! op-ch)
data (<! data-ch)]
(put! result-ch (op data))))

显然这是行不通的,因为它需要两个 channel 具有相同的频率。

(参见 http://rxmarbles.com/#withLatestFrom )

最佳答案

使用alts!你可以完成你想要的。

下面显示的 with-latest-from 实现了 withLatestFrom 中的相同行为。来自 RxJS(我认为: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"

关于clojure - 如何使用 core.async channel 对 Rx 的 `withLatestFrom` 进行建模?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31144010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com