(alt! & clauses)
Makes a single choice between one of several channel operations, as if by alts!, returning the value of the result expr corresponding to the operation completed. Must be called inside a (go ...) block. Each clause takes the form of: channel-op[s] result-expr where channel-ops is one of: take-port - a single port to take [take-port | [put-port put-val] ...] - a vector of ports as per alts! :default | :priority - an option for alts! and result-expr is either a list beginning with a vector, whereupon that vector will be treated as a binding for the [val port] return of the operation, else any other expression. (alt! [c t] ([val ch] (foo ch val)) x ([v] v) [[out val]] :wrote :default 42) Each option may appear at most once. The choice and parking characteristics are those of alts!.
;; attempts to put trade on channel trade-ch within 1 second.
;; yields :timed-out or :sent.
(let [timeout-ch (timeout 1000)]
(alt!
timeout-ch :timed-out
;; note use of double-nested vector; [trade-ch trade]
;; would be interpreted as two channels to take from, resulting
;; in an odd error.
[[trade-ch trade]] :sent))
(def trade-ch (chan))
(go-loop []
(<! (timeout 1000))
(print (<! trade-ch))
(recur))
(go
(let [timeout-ch (timeout 1000)
trade 100]
(->
(alt!
[[trade-ch trade]] :sent
timeout-ch :timed-out)
print))) ;;eval this at will
;;printout example
core.js[38]:\t
:sent
core.js[38]:\t
100
core.js[38]:\t
100
core.js[38]:\t
:sent
core.js[38]:\t
:timed-out
core.js[38]:\t
:timed-out
core.js[38]:\t
:timed-out
core.js[38]:\t
:timed-out
core.js[38]:\t
:timed-out
core.js[38]:\t
:timed-out
core.js[38]:\t
:sent
core.js[38]:\t
100
;; Reading from multiple channels, handling whichever gets data first
(use 'clojure.core.async)
(def result-chan (chan))
(def error-chan (chan))
(def dont-care-chan (chan))
(go
(alt!
result-chan ([result] (println! (str "Success: " result)))
error-chan ([error] (println! (str "Error: " error)))
dont-care-chan (println "Don't care about the value!")))
;; Given
(put! result-chan "Some result")
;; Output
;; Success: Some result
;; Given
(put! error-chan "Some error")
;; Output
;; Error: Some error
;; Given
(put! dont-care-chan "Some value")
;; Output
;; Don't care about the value!