Skip to content

clojure.core.async/alt!

View this page on ClojureDocs

Type: macro Added: Clojure unknown Examples: 4 Runnable: 0
([& 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!.

Examples

by hlship on . May have evaluation errors.
by boxxxie on . May have evaluation errors.
by spiralman on . May have evaluation errors.
by cstml on . May have evaluation errors.

Note by jzwolak

alt! does not take a vector of ports as per alts!. alts! takes a vector of ports. alt! takes a literal vector of ports only. Any symbol containing a value that is a vector of ports will not work with alt! even though such a value will work with alts!.

(ns examples.failing-async
  (:require [clojure.core.async :refer [chan go alt! >! alts!]]))

(def c1 (chan))
(def c2 (chan))
(def two-chans [c1 c2])

(println (vector? two-chans))

; Fails
(go (loop []
      (alt! two-chans ([v c] (println "got v =" v)))
      (recur)))

(go (>! c1 "hi on alt! two-chans"))

; Succeeds (must comment out above failing code for this to work)
(go (loop []
      (alt! [c1 c2] ([v c] (println "got v =" v)))
      (recur)))

(go (>! c1 "hi on alt! [c1 c2]"))

; Succeeds
(go (loop []
      (let [[v c] (alts! two-chans)]
        (println "got v =" v))
      (recur)))

(go (>! c1 "hi on alts! two-chans"))

See also


Content from the matching ClojureDocs page, with authors credited on each contribution.